...

View Full Version : Random number not randomizing in while loop



dannystones
10-17-2011, 09:35 PM
The program functions correctly apart from the random number function in the while(cscore<=32) and I cant work out why as its working in the while (ans!='n') loop. Basically it prints out the same number over and over instead of a different one everytime.


#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>

int main(){

char ans = 'y';
int uscore = 0;
int cscore = 0;
int randnum;

while(ans!='n'){

printf("Your score is: %d", uscore);
printf("\nDo you want to take another number? ");
scanf("%c", &ans);
getchar();

if (ans=='y'){

srand(time(NULL)); /* Initialize random seed */
randnum = rand()%21+1; -/* Generate random number */
printf("You get the number: %d\n", randnum);
uscore = uscore+randnum;

if (uscore>42){

printf("Your score is %d \nYou bust!!", uscore);
return 0;

}
}
}

printf("Now the computer plays");

while(cscore<=32){

srand(time(NULL)); /* Initialize random seed */
randnum = rand()%21+1; -/* Generate random number */
printf("\nThe computer gets the number: %d", randnum);
cscore = cscore+randnum;

if (cscore>42){

printf("\nComputer busts");
printf("\nYou Win!\n");
return 0;

}
}

printf("\nThe computers score is %d", cscore);

if (uscore>cscore){

printf("\nYou Win!\n");

}

else if(uscore<cscore){

printf("\nYou Lose!\n");

}

else {

printf("\nYou draw\n");}

return 0;
}

oracleguy
10-17-2011, 09:41 PM
Move your call to srand to be before the while loop. You only need to initialize the RNG once per execution of your program.

The reason it works in the first loop is that user input causes a long wait (in terms of computers) which means the RNG is seeded with different values of time. However in the 2nd loop the RNG keeps being seeded with the same number.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum