C语言数字猜谜游戏问题求助:无论输入何值均判定错误
Hey there! Let's troubleshoot your number guessing game issue. I see your code snippet cuts off at char instri..., but based on your description that any input gets incorrectly marked as wrong, here are the most common causes and fixes:
1. Mismatched Variable Types
This is the #1 culprit here! rand() returns an integer (int), but if you're storing your user's guess in a char variable (like your cut-off char instri... suggests), the values won't compare correctly.
You need to use int for both the target number and the user's guess. Here's a corrected core structure:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); // Generate a random number between 1 and 100 (adjust range as needed) int target_number = rand() % 100 + 1; int user_guess; printf("Guess a number between 1 and 100: "); // Use %d to read an integer, and pass the address of user_guess with & scanf("%d", &user_guess); if (user_guess > target_number) { printf("too high\n"); } else if (user_guess < target_number) { printf("too low\n"); } else { printf("You guessed it right!\n"); } return 0; }
2. Unrestricted Random Number Range
rand() spits out a number from 0 to RAND_MAX (usually 32767). If you don't narrow it down to a reasonable range (like 1-100), your user's guess will almost never match. Use this formula to set your target:int target = rand() % [upper_limit] + [lower_limit];
For example, rand() % 50 + 1 gives numbers from 1 to 50.
3. Incorrect Input Reading
If you're using the wrong format specifier in scanf, the guess value will be garbage (uninitialized), leading to wrong comparisons. Always match the specifier to your variable type:
- For
int: Use%dand pass the address with&(likescanf("%d", &user_guess);) - Avoid using
charfor numeric guesses—they can't hold multi-digit numbers!
4. Broken Comparison Logic
Double-check your if/else blocks to make sure you're not mixing up the conditions. For example, accidentally writing if (target > user_guess) when you mean to check the other way around would flip your feedback, but if all guesses are wrong, this is less likely than the type mismatch.
- Swap any
charvariables forintwhere you're storing numbers (target or guess) - Add the range restriction to your
rand()call - Verify your
scanfuses%dand includes the&before the variable name - Test with a hardcoded target first (like
int target = 42;) to see if the comparison works—if it does, the issue is with your random number setup
If you can share the full, uncut code, I can pinpoint the exact line causing the problem!
内容的提问来源于stack exchange,提问作者Red

