【发布时间】:2012-11-13 03:46:06
【问题描述】:
这是我的代码:
#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;
}
为什么main()中的所有变量都是同一个数字?
我只得到这样的输出:
1
1
1
1
1
1
1
1
【问题讨论】:
-
您应该只初始化 (
srand) 一次(在整个程序中,除非您知道自己在做什么以及为什么)并且a = rand() % 6;永远不会返回 6(但是将返回 0)。有关详细信息,请阅读文档。我知道。我知道:不得已。但你必须这样做。真的。 -
另一个reading the manual可以避免的问题...
-
另一个本可以避免的评论...嗯...只是避免...