为什么我的第一次推出我的程序不是随机的?

时间:2016-09-17 20:21:39

标签: c++ random dice

这个程序是一个掷骰子游戏。该程序运行完美,除了每次程序启动时,它给我相同的随机数,但如果你继续玩游戏并开始一个新游戏而不退出控制台,第一个滚动数字显然是随机的看看我如何预测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;
}

1 个答案:

答案 0 :(得分:3)

class DiceClass{
public:
   DiceClass(){
      srand(time(0));
   }

   int firstdiceroll = 2+rand()%11;

   // etc.
};

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