【发布时间】:2012-06-28 14:05:25
【问题描述】:
我制作的小游戏有问题。
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int span = 100;
srand(time(0));
int TheNumber = static_cast<double> (rand()) /RAND_MAX * (span -1) +1;
cout << "You need to guess the number between 1 and " << span << endl;
int mynumber;
int numberofAttempts = 0;
do {
cout << ++numberofAttempts <<" Attempt: ";
cin >> mynumber;
if (mynumber > TheNumber)
cout <<"Lower!" << endl;
else if (mynumber < TheNumber)
cout <<"Higher!" << endl;
} while (mynumber != TheNumber);
cout << "SUCESS!!!" << endl;
return 0;
}
游戏应该生成一个介于 0-100 之间的随机数,你应该猜到它。运行此代码 15-20 次后,相同的数字甚至生成了 8 次(在我的例子中是数字 2)。
我知道没有绝对随机数并且它使用一些数学公式或其他东西来获得一个。我知道使用srand(time(0)) 使它依赖于当前时间。但是我如何让它“更”随机,因为我不希望发生我上面提到的事情。
我第一次运行它的结果是 11,再次运行后(猜对了数字后),它仍然是 11,即使时间改变了。
【问题讨论】:
-
我刚刚更新了最后一部分,经过猜测(肯定过了几秒钟),数字还是一样。
-
将TheNumber的声明改为
int TheNumber = rand() % 100 + 1; -
@jrok,不好的建议。众所周知,
rand()的低位不是随机的。 -
我很确定它会比他现在拥有的要好得多。
rand()的问题可能超出了当前 Q 和 OP 的经验范围,你不觉得吗? -
@FredOverflow:这就是罪魁祸首!