in c++ how does one create a code to generate a random number that is less than x?
Printable View
in c++ how does one create a code to generate a random number that is less than x?
use the standard function rand()?
--
Mats
Use srand() to seed, and rand() to actually generate the number. Use the modulus operation on the output of rand() to control the maximum value you will receive.
In this example, the number will be between 0 and 9.Code:int x = rand() % 10;
thanks a lot!
k it works and i have written the code
i did some research and found out the necessary header files..but i have a problemCode:#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int a=rand()%10;
cout<<a;
getch();
return 0;
}
the problem goes like this
1->i compile the file
2->i run the file and say i get 10 as an output
3-> i close the window and again run the file
4->now i get the same output 10...
could this output be changed ?
As suggested, use srand() with a suitable seed - that "initiates the random sequence".
Try looking at www.eternallybefuzzled.com for some examples of random number generation.
--
Mats
Befuzzled? ;)
www.eternallyconfuzzled.com