对于我当前的项目,我创建了一个应该根据我的代码生成的随机整数而改变的事件,唯一的问题是我似乎总是得到相同的路径。总之,我希望它发生任何事件的几率为50%。 谢谢,西蒙
random1 = rand() % 1 + 0;
if (random1 == 0) {
int choice4;
cout << "Your character screams at the top of his lungs, " << endl;
cout << "this causes the dragon to immediately to bow in fear..." << endl;
cout << "It turns out dragons are very sensitive to hearing....." << endl;
system("pause");
cout << "\nIt seems the dragon is requesting you ride it!\n" << endl;
cout << "Will you ride it?\n" << endl;
cout << "1. Ride it" << endl;
cout << "2. Or Wait here." << endl;
cin >> choice4;
cin.ignore();
system("cls");
if (choice4 == 1){
Ending();
}
}
else if (random1 == 1) {
cout << "Your character screams at the top of his lungs, " << endl;
cout << "eventually your breath gives out and you die because of lack of oxygen." << endl;
system("pause");
gameover();
答案 0 :(得分:6)
到目前为止,所有其他答案都提到需要使用srand()
来初始化随机数生成器,这是一个有效点,但不是您遇到的问题。
你的问题是你的程序计算随机数的模数和1,它总是等于0,因为对于任何整数n,
n % 1 == remainder of the integer division of n by 1
== n - (n / 1)
== 0
所以,替换这个:
random1 = rand() % 1 + 0;
用这个:
random1 = rand() % 2;
你会得到一些你想要的东西。我说&#34;有点&#34;因为还有其他需要考虑的问题,例如随机数生成器初始化(srand()
),使用rand()
而不是更精细的RNG等等。
答案 1 :(得分:-2)
rand()只能生成伪随机数,也就是说,同一种子会生成相同的序列。
只需使用srand()初始化种子,这是一个例子
#include <cctype>
#include <sys/time.h>
struct timeval cur_tm;
gettimeofday(&cur_tm, NULL);
seed = static_cast<unsigned int>(cur_tm.tv_usec);
srand(seed);