为什么每次for循环的输出都完全相同
Why is the output of the for loop the exact same result each time?
我希望这个程序生成4个不同的4个随机数系列。该程序目前正在为每个系列输出相同的数字。知道发生了什么事吗?我认为这与种子有关,但我不知道什么。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int lotArr[6];
int j = 0;
int k = 0;
int m = 0;
int n = 0;
int i = 0;
bool crit = false;
//interates through 4 sequences
for(int i = 0; i < 4; i++ )
{
srand(time(NULL));
//generates each number in current sequence
for(m = 0; m < 4; m++)
{
lotArr[m] = rand() % 30 + 1;
}
//output
for(n = 0; n < 4; n++)
{
cout << lotArr[n] << " ";
}
cout << endl;
}
return 0;
}
这是因为时间(null(在几秒钟内返回unix时间戳。现在,您的每个外部循环都以少于一秒钟的速度执行。因此,srand(时间(null((本质上将种子设置为相同的每个环。我建议乘坐srand(时间(null((;从循环中出来,你会没事的。这样的东西:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int lotArr[6];
int j = 0;
int k = 0;
int m = 0;
int n = 0;
int i = 0;
bool crit = false;
srand(time(NULL));
//interates through 4 sequences
for(int i = 0; i < 4; i++ )
{
//generates each number in current sequence
for(m = 0; m < 4; m++)
{
lotArr[m] = rand() % 30 + 1;
}
//output
for(n = 0; n < 4; n++)
{
cout << lotArr[n] << " ";
}
cout << endl;
}
return 0;
}
相关文章:
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 如何修复输出日志中的"EnableInput can only be specified on a Pawn for its Controller"错误
- 如何在 c++ 中使用 for 循环输出矢量中的所有对象
- 我将如何保存此 for 循环的输出
- 尝试使用嵌套的 for 循环进行某些输出
- 无法在 for 循环中的 pow 函数上输出答案
- For-Loop帮助获得错误的输出
- 为什么每次for循环的输出都完全相同
- 如何使用 for 循环将元素加载到我的每个数组中,然后将每个数组的总和输出到一个 sum 数组中
- 为什么每次“for”迭代都会输出 4 次
- 将在 C++ 中输出多维数组内容的 for 循环的结构是什么
- 我无法理解为什么输出在这个 for 循环中出现 10
- for 循环中的迭代次数错误.也得到意想不到的输出
- 来自 for 循环的奇数输出
- 尝试使用for循环输出10行
- for循环错误地输出指数
- Clang 输出错误"no matching construct for initialization"
- 嵌套For循环和输出星号
- C++For循环初学者输出错误