理解srand(time(0))行为

时间:2018-03-25 18:02:18

标签: c++ random

以下是我尝试创建一个简单的高低游戏。我只是不明白为什么下面给出的代码在do-while循环中放置srand(time(0))时表现不同,也就是说,为什么修改后的代码在循环的每次迭代中生成相同的随机数?

#include<iostream>
#include<cstdlib>
#include<ctime>

int main(){
    int c;
    srand(time(0));
    do{
        int i, num;
        int min = 1;
        int max = 10;
        float fraction = 1.0 / (RAND_MAX+ 1); 
        num = min + (max-min + 1) * (rand() * fraction);
        for (int j=0;j<20;j++){
            std::cout<<"*";

        }
        std::cout<<"THE GUESSING GAME!";
        for (int j=0;j<20;j++){
            std::cout<<"*";

        }

        std::cout<<"\nRange of guess should be 1 to 10 inclusive\n ";
        std::cout<<"Guess a number: ";
        std::cin>>i;

        while(1){
            if (i==num){
                std::cout<<"Yeah! you guessed it right! "<<i<<" is the right number "<<std::endl;
                break;
            }else if (i<num){
                std::cout<<"Too low\n";
                std::cout<<"Guess another number: ";
                std::cin>>i;

            }else{
                std::cout<<"Too high\n";
                std::cout<<"Guess another number: ";
                std::cin>>i;

            }

        }

        std::cout<<"\nWanna play again? Press 1 to continue and 0 to exit: ";
        std::cin>>c;
    }while(c);
        return 0;
}

0 个答案:

没有答案