dannystones
10-17-2011, 08: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;
}
#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;
}