随机化不会发生在while循环中。如何解决这个问题? C ++

时间:2016-02-21 00:27:41

标签: c++ procedural-programming

当if / else出现在while循环中时,我无法进行随机化工作。这是代码:

#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;

    }
}

我希望dice_value始终是随机的,无论是&#39; c&#39;或者&#39; h&#39;但是当循环重复时,该值不会改变。我哪里出错了?

1 个答案:

答案 0 :(得分:3)

您需要移动此声明:

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

进入while循环。