为什么rand()在这个for循环中使用srand(time(null))返回相同的值? [英] Why does rand() return the same value using srand(time(null)) in this for loop?
本文介绍了为什么rand()在这个for循环中使用srand(time(null))返回相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
#include<iostream>
#include "time.h"
using namespace std;
void printRandomNumber()
{
srand(time(NULL));
cout << rand() % 3;
}
int main()
{
for(int i=0; i<=5; i++)
{
printRandomNumber();
}
system("pause");
}
输出是相同的数字重复六次,我想它打印
The output is the same number repeated six times, I would like it to print out a mix of numbers.
推荐答案
因为你每次都使用相同的值播种– time
只有二级精度,我相信您的计算机可以在一秒钟内处理这六个循环迭代。 ; - ]
Because you're seeding with the same value each time – time
only has second-level precision, and I'm quite sure your computer can process those six loop iterations within one second. ;-]
在程序开始时种子
Seed once, at the beginning of the program.
这篇关于为什么rand()在这个for循环中使用srand(time(null))返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文