Hello Every one !
This program is producing some strange output as it is only generating x = 6 :(,can some through some light that why is it behaving like this ?

#include <iostream>
#include <stdlib.h>
using namespace std ;
main ()
{
     // Random Number Program 
     int num,x ;
     cout << "Please Enter a no between 1 to 6 " ;
     cin >> num ;
     x = rand() % 6 + 1 ;
     if ( num == x)
     cout << "Congratulations!You WON " ;
     else 
     cout << " You Lose " ;
}

Hello Every one !
This program is producing some strange output as it is only generating x = 6 :(,can some through some light that why is it behaving like this ?

Simple, the program is choosing a random number but each time you run it, it will use that same number. The Below code will set the staring point of generating a random number to be different after each run. Simply add it to you existing code.

#include <ctime>
time_t t;
     time(&t);
     srand(t);

This will insure it uses a different number each time...Try it out:)

Edited 6 Years Ago by The ICE Man: n/a

>can some through some light that why is it behaving like this ?
It would truly suck for testing if rand weren't default seeded to a predictable value. As such, if you don't call srand, the program will behave as if you called srand(1) .

>time_t t;
>time(&t);
>srand(t);

The one-liner is generally preferred:

srand((unsigned)time(0));

But this is C++. We can do better by wrapping everything in a class and letting the object do all of the grunt work:

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

class Random {
public:
    Random(bool seed=true)
    {
        if (seed)
        {
            std::srand((unsigned)time(0));
        }
    }

    double get()
    {
        return std::rand() * (1.0 / (RAND_MAX + 1.0));
    }

    int next(int hi)
    {
        return (int)(get() * hi);
    }

    int next(int lo, int hi)
    {
        return (int)(lo + get() * (hi - lo));
    }
};

int main()
{
    Random r;

    for (int i = 0; i < 10; i++)
    {
        std::cout<< r.next(1, 6) <<'\n';
    }
}
Comments
Good One :)
This question has already been answered. Start a new discussion instead.