Problem: Acquiring a random integer number between 1 and 100. (rand() % 100) + 1 has failed. Suggestions?
Story: I'm trying to write a simple guessing game; I think of a number, an integer, betwixt 1 and 100, while you try to guess it. I use (rand() % 100) + 1 to get the (supposedly) random number. Over the dozen or so times I've done it, I have consistently gotten 84 as the secret number. By my calculations, that's roughly a chance of 1 in 10^24; one in a million billion billion. Clearly, there's a problem somewhere. My full code follows.
Code:
#include <stdio.h>
main () {
int guess, high, low;
high = 100;
low = 0;
char line[80];
printf("I'll think of a number and you try to guess it.\n");
printf("If you get it right, you get a prize. Come on, friend. ");
while (1) {
int secret = rand() % 100 + 1;
printf("Enter your guess.\n");
printf("Hint: It's between %d and %d\n", low, high);
(void)fgets(line, sizeof(line), stdin);
(void)sscanf(line, "%d", &guess);
if (guess == secret) {
printf("Bingo!\n");
break;
}
if (guess > secret) {
high = guess;
printf("Sorry, too low.\n");
} else {
low = guess;
printf("Sorry, too high.\n");
}
}
return(0);
}