我正在制作程序来配置我的wifi,因为我经常往返于其他网络。我正在生成一个随机数,它是192.168.0。*序列中的最后一个数字。现在,当我运行不带文件i / o的代码时,随机数会很好地生成,但是,当我运行带文件i / o的代码时,它只会生成2或144。有人可以告诉我为什么会这样,也许提供一个解。谢谢。以下是生成随机数并与之前使用的数字进行比较的代码。

//initialise variables so rndm>2 and <253
int rndm, minNum=2, maxNum=253, iHistory;
bool loop=0;


while(loop==0){
  std::cout<<"One Moment please, generating random number...\n";
  //generate random number
  rndm = ((double) rand() / (RAND_MAX+1)) * (maxNum-minNum+1) + minNum;

  //Read number from history file
  ifstream inputFile("History.txt");
  string line;

  while (getline(inputFile, line)) {
      istringstream ss(line);
      string history;
      ss >> history ;
      iHistory=atoi(history.c_str());
      //If random number was used before, loop
      if(iHistory==rndm){
          loop=0;
      }
      else{
          loop=1;            //else continue
      }
   }
}
//Write random number to file
ofstream myfile;
myfile.open ("History.txt");
myfile << rndm;
myfile.close();

std::cout<<"Random number is: "<<rndm<<"\n\n";

最佳答案

我成功了,我只是改变了随机数发生器。

int min = 2;
int max = 253;
int rng = 0;
srand(unsigned(time(NULL)));

rng = rand() % max;
if(rng == min-1 || rng == max-1){ rng++; }


确保阅读种子。


http://www.cplusplus.com/reference/cstdlib/srand/

10-05 20:12