dimanche 25 mars 2018

Understanding srand(time(0)) behaviour [duplicate]

Given below is my attempt to create a simple high-low game. I just don't understand why the code given below behaves differently when I place the srand(time(0)) inside the do-while loop, i.e, why does the modified code generate the same random number in each iteration of the loop?

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




Aucun commentaire:

Enregistrer un commentaire