Sadij
Sadij

Reputation: 51

Randomization doesn't occur in while loop. How to fix this? C++

I can't get randomization to work when if/else is present inside this while loop. Here is the code:

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main(){
    srand(time(0));
    int dice_num=(rand()% 6+1)+(rand()%6 +1);
    char dice_value,your_guess;


    while(true){

    //Dice Conversion
        if(dice_num%2==0) dice_value='c';
         else dice_value='h';

//User Input
                cout<<"Enter 'c'(even) or 'h'(odd)or 'e' to exit : ";
                cin>>your_guess;

        //User Math
                if(your_guess==dice_value){

                    cout<<"You Won!"<<endl;
                }else {

                    cout<<"You Lost!"<<endl;
                }

                cout<<your_guess<<dice_value<<endl;
                if(your_guess=='e') break;

    }
}

I want dice_value to always be random whether 'c' or 'h' but when the loop repeats, the value does not change. Where did I go wrong?

Upvotes: 0

Views: 55

Answers (1)

moswald
moswald

Reputation: 11677

You need to move this statement:

int dice_num=(rand()% 6+1)+(rand()%6 +1);

into your while loop.

Upvotes: 3

Related Questions