随机整数似乎总是相同的

C++ Random integer seems to always be the same

本文关键字:整数 随机      更新时间:2023-10-16

对于我当前的项目,我已经创建了一个事件,应该根据我的代码生成的随机整数而改变,唯一的问题是我似乎总是得到相同的路径。简而言之,我希望这两个事件发生的概率都是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();

到目前为止,所有其他答案都提到需要使用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;

,你就会得到你想要的东西。我说"有点"是因为还有其他问题需要考虑,例如随机数生成器初始化(srand()),使用rand()而不是更复杂的rng等。

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);