为什么我的第一个项目不是随机的?

Why is my first roll out of my program not random?

本文关键字:随机 我的 第一个 项目 为什么      更新时间:2023-10-16

这个程序是一个掷骰子的游戏。程序运行得非常好,除了每次程序启动时,它都会给我相同的随机数,但如果你继续玩游戏并在不退出主机的情况下开始新游戏,那么第一个掷出的数字显然是随机的,因为我无法预测again()函数之后它会是什么,但当代码首次启动时,第一个掷出的数字总是10。我一直在试图自己解决这个问题,我似乎找不到任何一个有骰子游戏编码的人,但也许有人可以在这里帮助我。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//main prototype
int main();
//score system
int wins = 0;
int loses = 0;
int again(){
    int answer;
    cout << "nWould you like to play another round? (1=y,2=n)n" << endl;
    cin >> answer;
    cout << endl;
    cout << endl;
    if(answer==1){
        main();
    }else if(answer==2){
        cout << "thanks for playing homie" << endl;
        return 0;
    }else{
        cout << "I'm sorry what?" << endl;
        again();
    }
}//end of again
class DiceClass{
public:
    DiceClass(){
        srand(time(0));
    }
    int firstdiceroll = 2+rand()%11;
    void PhaseOne(){
        cout << "Lets play some craps. n" << endl;
        system("pause");
        cout << endl;
        cout << "You rolled " << firstdiceroll << "." << endl;
        if(firstdiceroll==7 || firstdiceroll==11){
            cout << "You win!!" << endl;
            wins++;
            cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
            again();
        }
        else if(firstdiceroll==2 || firstdiceroll==3 || firstdiceroll==12){
            cout << "You lose!" << endl;
            loses++;
            cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
            again();
        }
        else{
            cout << "Rolling again!n" << endl;
            system("pause");
            cout << endl;
            PhaseTwo();
        }
    } //ends PhaseOne
    void PhaseTwo(){
        int seconddiceroll = 2+rand()%11;
        cout << "You rolled " << seconddiceroll << endl;
        if(firstdiceroll==seconddiceroll){
            cout << "You win!!" << endl;
            wins++;
            cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
            again();
        }
        else if(seconddiceroll==7){
            cout << "You lose!" << endl;
            loses++;
            cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
            again();
        }
        else{
            cout << "Rolling again." << endl;
            system("pause");
            cout << endl;
            PhaseTwo();
        }
    } //ends PhaseTwo
}; //ends DiceClass
int main()
{
    DiceClass DObject1;
    DObject1.PhaseOne();
    return 0;
}
class DiceClass{
public:
   DiceClass(){
      srand(time(0));
   }
   int firstdiceroll = 2+rand()%11;
   // etc.
};

类的成员变量在进入构造函数体之前被初始化。因此,在更改随机数序列之前设置firstdiceroll