C语言猜数字游戏:counter变量无法统计尝试次数问题求助
Hey there! Let's fix that counter issue in your guessing game—no worries, it's a super common slip-up when you're starting out with loops and counters.
First, let's break down why your counter isn't working right:
Right now, you only increment counter when the user guesses the correct number. But every time the user types in a guess (whether it's too high, too low, or spot-on), that counts as one try. So we need to move that counter increment to a place where it runs every single loop iteration, not just the final correct guess.
Also, your code has a small syntax bug with how you declared counter and structured the main() function—let's clean that up too, plus add some small quality-of-life tweaks like line breaks for readability.
Here's the fixed code with explanations:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int counter = 0; // Initialize counter at the start of the function int num, guess; srand(time(0)); num = rand() % 200 + 1; printf("Guessing game, guess the number between 1 and 200\n"); do { scanf("%d", &guess); counter++; // This runs EVERY time the user makes a guess—perfect! if (guess > num) { printf("Too high\n"); } else if (guess < num) { // Using else if makes logic cleaner and avoids redundant checks printf("Too low\n"); } else { // Only runs if guess == num (the only remaining case) printf("Your guess is correct! It took you %d tries\n", counter); } } while (guess != num); return 0; }
Key changes I made:
- Moved
counter++right afterscanf: This ensures every guess (correct or not) gets counted as a try. - Fixed variable declaration and
main()structure: Variables need to be declared inside the function's curly braces, not right aftermain(). - Added missing header files:
rand(),srand(), andtime()require<stdlib.h>and<time.h>to work properly. - Used
else ifinstead of separateifstatements: This makes the logic flow better and prevents unnecessary checks once we know the guess is correct. - Added
\nto print statements: Keeps output from clumping together and makes the game feel more polished.
内容的提问来源于stack exchange,提问作者Jordan Crombie

