I have the code below. The problem is with variable r, which first holds a random number between 1-10. Later it is compared inside a loop to a user input number. The loop ends when the user guesses the randomly generated number. I am using short type for the guess, and int for the randomly generated number r. The point is that after the first guess of the user, r becomes 0 and I don't know why. This problem does not happen if guess is an int.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
srand(time(NULL));
int r = (rand()%10)+1;
short guess = -1;
printf("%d\n", r);
while ((guess)!= r){
printf("%d\n", (int) guess);
printf("%d\n", guess);
printf("%d\n", r);
printf("Give me a number from 1 to 10: ");
scanf("%d",&guess);
if (guess> r){
printf("The number is lower\n");
}
else if (guess<r){
printf("The number is higher\n");
}
else {
printf("Corrent!\n");
}
}
return 0;
}
An output example would be:
7
-1
-1
7
Give me a number from 1 to 10: 5
The number is lower
5
5
0
Give me a number from 1 to 10:
Aucun commentaire:
Enregistrer un commentaire