random number in while loop [C programming] -
this question has reply here:
c++ random int function 3 answersi'm trying create 2 random numbers (between 0-4 , 0-10) in each time cycle occurs, give same number. if run programme multiple times, gives different numbers, while cycle generates same 2 numbers. thanks.
int random(int range){ int num; srand(time(null)); num = rand() % range; homecoming num; } int main(){ int cnt = 0; int i; int j; while (cnt <= 20) { = random(5); j = random(10); printf("%d\n",i); printf("%d\n",j); printf("\n"); cnt += 1; } homecoming 0; }
you need seed random number generator once.
so run line outside of random function:
srand(time(null));
.. in main function instead:
int random(int range){ int num; num = rand() % range; homecoming num; } int main(){ int cnt = 0; int i; int j; // seed random number generator srand(time(null)); while (cnt <= 20){ = random(5); j = random(10); printf("%d\n",i); printf("%d\n",j); printf("\n"); cnt += 1; } homecoming 0; }
c loops random
No comments:
Post a Comment