Whenever I run this code, I get a same result.
Program
#include<stdlib.h>
int main(int agrc, const char *argv[]) {
int i = rand();
printf("%d\n",i);
for(i=0;i<10;i++) {
printf("%d\n",rand());
}
}
Result:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
I ran this on mingw
. Actually I am learning Objective-C
Please help me.
You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()
For example
srand(time(NULL));
rand();//now returns a random number
The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.
So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With