C++随机整数似乎总是相同的

Mak*_*ako -3 c++ random events integer

对于我当前的项目,我创建了一个事件,该事件应该根据我的代码生成的随机整数而改变,唯一的问题是我似乎总是得到相同的路径.总之,我希望它发生任何事件的几率为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();
Run Code Online (Sandbox Code Playgroud)

Mar*_* J. 6

到目前为止,所有其他答案都提到需要使用srand()初始化随机数生成器,这是一个有效的点,但不是你遇到的问题.
你的问题是你的程序计算随机数的模数和1,它总是等于0,因为对于任何整数n,

n % 1 == remainder of the integer division of n by 1 
      == n - (n / 1) 
      == 0
Run Code Online (Sandbox Code Playgroud)

所以,替换这个:

random1 = rand() % 1 + 0;
Run Code Online (Sandbox Code Playgroud)

有了这个:

random1 = rand() % 2;
Run Code Online (Sandbox Code Playgroud)

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