How to generate a random number in C++?

后端 未结 11 1533
萌比男神i
萌比男神i 2020-11-22 11:14

I\'m trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using



        
11条回答
  •  误落风尘
    2020-11-22 11:41

    Here is a solution. Create a function that returns the random number and place it outside the main function to make it global. Hope this helps

    #include 
    #include 
    #include 
    int rollDie();
    using std::cout;
    int main (){
        srand((unsigned)time(0));
        int die1;
        int die2;
        for (int n=10; n>0; n--){
        die1 = rollDie();
        die2 = rollDie();
        cout << die1 << " + " << die2 << " = " << die1 + die2 << "\n";
    }
    system("pause");
    return 0;
    }
    int rollDie(){
        return (rand()%6)+1;
    }
    

提交回复
热议问题