Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Random number not randomizing in while loop

    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.

    Code:
    #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;
    }

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    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.
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •