程序总是产生相同的价值?

Posted

技术标签:

【中文标题】程序总是产生相同的价值?【英文标题】:Program always producing same value? 【发布时间】:2011-09-21 01:44:39 【问题描述】:

我的程序的重点是将数字 1 - 1,000,000 写入文本文件,生成一个介于 1 和 1,000,000 之间的随机数,在文本文件中搜索该行,取值,然后平方(这只是对我来说是一个练习,它没有实际应用)。问题是每当我运行它时,值都保持不变,但rand() 函数是由time(0) 播种的。我怀疑这是一个垃圾值,但我不知道它来自哪里(我没有使用 GDB 或任何其他独立调试器的经验)。这是我的源代码:

#include <fstream>
#include <ctime>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main(int argc, char** argv)
    ofstream file("log.txt", ios::app);
    ofstream programLog("programlog.dat", ios::app);
    cout << "Test Start" << endl;
    programLog << "Test Start" << endl;
    cout << "Log file created" << endl;
    programLog << "Log file created" << endl;
    ifstream readFile("log.txt");
    int foundNum;
    std::string line = "";
    unsigned int loopCount = 1000000;
    unsigned int numToSearch;
    const unsigned short min = 1;
    const int max = 1000000;
    unsigned int randomLine = 0;

    for(int i = 0; i <= loopCount; i++)
        file << i << endl;
    

    //select random line
    srand((unsigned)time(0));

    while(!(randomLine > min) && !(randomLine < max))
        randomLine = (unsigned)rand();
        programLog << randomLine;
        int newlines = 0;
        //size_t found;
        while(getline(readFile, line))
            if(line.find("\n") != string::npos)
                newlines++;
            if(newlines == randomLine)
                numToSearch = atoi(line.c_str());
        

    

    programLog << "Random line selected" << endl;

    //read line
    while(std::getline(readFile,line))
        if(atoi(line.c_str()) == numToSearch)
            foundNum = numToSearch;
            break;
        
        else
            continue;
    

    //square it
    const unsigned int squared = foundNum*foundNum;

    programLog << squared;
    readFile.close(); //end read
    file.close(); //end log
    programLog.close(); //end programlog
    return 0;

【问题讨论】:

file &lt;&lt; i &lt;&lt; endl; Rob 的规则:当你的意思是 '\n' 时,永远不要说 endl。见***.com/questions/5492380/… 【参考方案1】:

您永远不会在使用时进入 while 循环:

while(!(randomLine > min) && !(randomLine < max))

while 立即评估为 false。你应该使用:

while(randomLine < min || randomLine > max)

另外,为什么所有变量都有不同的类型?这可能会导致意外错误。您应该将它们更改为具有相同的类型。

【讨论】:

【参考方案2】:

randomLine 被初始化为 0,并且在到达 while 时仍然具有该值,因此循环体永远不会执行。

【讨论】:

以上是关于程序总是产生相同的价值?的主要内容,如果未能解决你的问题,请参考以下文章

产业链什么意思?产业链和产业价值链是相同概念吗?

一些有价值bug产生的思考

hadoop之魂--mapreduce计算框架,让收集的数据产生价值 (第4篇)

WidgetProvider 的 appWidgetIds[] 是啥?为啥总是得到它的价值0?

动态规划

用自己的行动去捍卫自己的价值观