C++ 相同的随机数
可能重复:C++ 相同的随机数,c++,random,srand,C++,Random,Srand,可能重复: 这是我的密码: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int attack() { srand((unsigned)time(NULL)); int hits=0; for (int i=0;i<=3;i++) { int a = rand() % 6; if (a==
这是我的密码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int attack() {
srand((unsigned)time(NULL));
int hits=0;
for (int i=0;i<=3;i++) {
int a = rand() % 6;
if (a==6 || a==5)
{
hits++;
}
}
return hits;
}
int main () {
int a=attack();
cout << a << endl;
int b=attack();
cout << b << endl;
int c=attack();
cout << c << endl;
int d=attack();
cout << d << endl;
int e=attack();
cout << e << endl;
int f=attack();
cout << f << endl;
int g=attack();
cout << g << endl;
int h=attack();
cout << h << endl;
}
srand()
应该在程序开始时调用一次(当然,在您开始调用rand()
之前的某个时刻)
通过每次输入函数时调用它(快速连续),可以将种子值重置为相同的值,这就是为什么会看到重复的数字
请注意,如果在程序运行时,时间单击到新的一秒,您可能偶尔会得到不同的数字,但这不太可能,因为该特定程序应该在远小于一秒的时间内完成
在第一次调用
attack()
之前,将srand()
调用移动到main()
,您应该只初始化(srand
)一次(在整个程序中,除非您知道自己在做什么和为什么)和a=rand()%6代码>永远不会返回6(但将返回0)。有关详细信息,请阅读文档。一、 知道。我知道:万不得已。但你必须这么做。你真的知道。另一个本可以避免的问题是…另一个本可以避免的评论…嗯…只是避免了。。。
1
1
1
1
1
1
1
1