You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 after scanf: 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 after main().
  • Added missing header files: rand(), srand(), and time() require <stdlib.h> and <time.h> to work properly.
  • Used else if instead of separate if statements: This makes the logic flow better and prevents unnecessary checks once we know the guess is correct.
  • Added \n to print statements: Keeps output from clumping together and makes the game feel more polished.

内容的提问来源于stack exchange,提问作者Jordan Crombie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:03:29