c++ - 程序在每次运行时生成相同的随机数?

标签 c++ random minesweeper

<分区>

我刚刚完成了一个扫雷类型游戏的编码,一切都很好,除了每次我运行该应用程序时,它都会生成相同的数字(我运行了 3 次不同的时间,将输出保存到 3 个文本文件并使用了 diff 命令,它没有发现任何差异)。它由 time(NULL) 播种,所以它应该每次都改变,对吗?

这是我的代码:

主要.cpp

#include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
#include "Minesweeper/box.h"
#include <cstdio>

int main(int argc, char** argv){
using namespace std;
bool gameOver  = false;
int x, y, score = 0;
const int HEIGHT = 10;
const int WIDTH = 10;
unsigned int Time = time(0);

cout << "Welcome to Minesweeper. " << endl;


//setup grid
Box grid[10][10];

for(int i = 0; i < WIDTH; i++)
for(int n = 0; n < HEIGHT; n++){
  unsigned int value = rand() %100 + 1;
  cout << value << endl;
  if(value <= 38){
grid[i][n].setFill(MINE);
//cout << i << "," << n << " is mined." << endl;
  }
  else
grid[i][n].setFill(EMPTY);
}

for(int r = 0; r < WIDTH; r++)
for(int l = 0; l < HEIGHT; l++)
  if(grid[r][l].getFill() == EMPTY)
cout << r << "," << l << " - EMPTY." << endl;
  else if (grid[r][l].getFill() == MINE)
cout << r << "," << l << " - MINE." << endl;

while(!gameOver){
cout << "Enter coordinates (x,y): ";
scanf("%i,%i",&x,&y);
if(grid[x][y].getFill() == MINE)
  gameOver = true;
else{
  cout << "Good job! (You chose " << x << "," << y << ")" << endl;
  score++;
}
}

cout << "You hit a mine! Game over!" << endl;
cout << "Final score: " << score  << endl;
getchar();

return EXIT_SUCCESS;
}

最佳答案

It's seeded by time(NULL)

如果是,我看不到。事实上,在您的代码中搜索它不会返回任何结果。默认行为,如果你没有明确播种,就像你用值 1 播种一样。

您需要明确声明如下内容:

srand (time (NULL));

main 的开头某处(并确保你这样做一次并且只做一次)。

请记住,这会使其依赖于当前时间 - 如果您在同一秒内启动多个作业(或任何您的时间分辨率),它们将从相同的种子开始。

来自 C 标准(C++ 基于这些兼容性功能):

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

关于c++ - 程序在每次运行时生成相同的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592129/

相关文章:

c++ - 为什么我尝试在结构内的 vector 内添加到结构内的 vector 会失败?

c++ - 理解Visual C++的rand()函数的算法

C++ Eclipse 调试器 : "Cannot find bounds of current function" and doesn't stop at breakpoints

c++ - 如何在您的库中包含外部库?

python - 生成给定范围内的随机时间戳?

c# - 如何计算给定索引周围 bool[,] 中的真实值?

c - POSIX C API 中的随机数

Python 从正态分布生成随机麦克斯韦分布

java - 二维数组长度错误

java - 扫雷对象 GUI