0

why the percentage of even and odd numbers generated by rand() is the same every time?

I wrote this code to figure out how random is the rand() function, maybe there are other ways to figure it out but i did what came to my mind first and with what knowledge i have of c++, but turns out the percentage of even and odd number are 48-52 every time. i ran it with code::block IDE and it's the same every time. I thought the percentage of even and odd numbers would be also random. please help me, what is it that i'm missing here?? #include <iostream> #include <cstdlib> using namespace std; int main() { int even = 0, odd = 0; for(int i = 0; i < 100; i++){ int x = rand(); if(x%2==0){ even++; } else{ odd++; } } cout << odd << " " << even ; return 0; }

14th Jul 2019, 6:51 PM
MdChy
6 Respuestas
+ 2
Add srand(time(NULL)); before for loop and enjoy 💪👌
14th Jul 2019, 7:07 PM
Dejan Francuz🥇
Dejan Francuz🥇 - avatar
+ 1
#include <random>
14th Jul 2019, 7:35 PM
Dejan Francuz🥇
Dejan Francuz🥇 - avatar
0
thank you for the answer Dejan Francuz. code: https://code.sololearn.com/cFU9joCfp3HS/#cpp Error: ..\Playground\: In function 'int main()': ..\Playground\:7:11: error: 'time' was not declared in this scope srand(time(98)); ^~~~ ..\Playground\:7:11: note: suggested alternative: 'ftime' srand(time(98)); ^~~~ ftime
14th Jul 2019, 7:43 PM
MdChy
0
#include <time.h>
14th Jul 2019, 7:53 PM
Dejan Francuz🥇
Dejan Francuz🥇 - avatar
0
sorry didn't catch you're 2nd post, here i figured something out: https://code.sololearn.com/cFU9joCfp3HS/#cpp so it's truly random when i put different arguments in srand() thanks for the help man.
14th Jul 2019, 7:53 PM
MdChy
0
MdChy nope, not really. Re-outputting that will give the exact same set of values because its dependent on a constant range of numbers. Just insert the correct libraries, cstdlib and ctime and use srand(time(NULL)); which generates a seed dependent on the change of current time and date.
14th Jul 2019, 9:35 PM
Choe
Choe - avatar