in c++ how does one create a code to generate a random number that is less than x?
in c++ how does one create a code to generate a random number that is less than x?
use the standard function rand()?
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Befuzzled?
www.eternallyconfuzzled.com
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens