+ 1

If the following code should run to giveout random number,Why does it give 41 everytime I run it...

include <iostream> #include <cstdlib> using namespace std; int main() { cout << rand(); }

8th Aug 2017, 12:17 PM
Ajaya Kumar Pradhan
Ajaya Kumar Pradhan - avatar
4 Answers
+ 6
it's a semi random number, I you want a real random number use this #include <iostream> #include <ctime> int main() } srand(time(NULL)); std::cout << rand(); } because the current time is now the seed of the rng generator
8th Aug 2017, 12:43 PM
johan beimers
johan beimers - avatar
+ 2
What Johan said, but use nullptr(C++11) instead of NULL though, just a good habit to get into :). He probably didn't use cstdlib because he wasn't required to, my compiler also doesn't require me to include it to use rand, if you do then just include it. Also keep in mind that you shouldn't use rand to generate numbers if your application really depends on randomness, because rand isn't random enough. I once did a simulator and it had wrong results just because I used rand.
8th Aug 2017, 12:51 PM
Dennis
Dennis - avatar
0
@johanbeginners Would there be no inclusion of cstlib in the help code you gave?
8th Aug 2017, 12:46 PM
Ajaya Kumar Pradhan
Ajaya Kumar Pradhan - avatar
0
Thanx dennis...
8th Aug 2017, 12:51 PM
Ajaya Kumar Pradhan
Ajaya Kumar Pradhan - avatar