在C中猜测游戏,无法获得尝试工作的次数,变量是" counter"

时间:2018-05-27 07:56:54

标签: c

不太确定如何使计数器变量工作以计算猜测正确数字所需的尝试次数。我试过把"反++;"在每个if语句中,但没有做任何事情。这是我自己编写的第一个代码,所以不要拖得太厉害请< 3

int main()
int counter
{
    int num , guess;
    counter = 0;
    srand(time(0));
    num = rand() % 200 + 1;

    printf ( "Guessing game, guess the number between 1 and 200" );

    do {
        scanf ( "%d" , &guess);
        if ( guess > num ){
        printf ( "Too high" );
    }

        if ( guess < num ){
        printf ( "Too low" );
    }

        if ( guess == num ){
        counter++;
        printf ( "Your guess is correct!, it took you %d tries" , counter );
        }


    }while (guess != num);

return 0;

}

1 个答案:

答案 0 :(得分:1)

只有在用户猜对时才会增加counter。你应该为每次尝试增加它。

您的程序中存在语法错误。这是一个更正版本:

#include <stdio.h>

int main() {
    int counter = 0;
    int num, guess;

    srand(time(0));
    num = rand() % 200 + 1;

    printf("Guessing game, guess the number between 1 and 200");

    while (scanf("%d", &guess) == 1) {
        counter++;
        if (guess > num) {
            printf("Too high\n");
        }
        if (guess < num) {
            printf("Too low\n");
        }
        if (guess == num) {
            printf("Your guess is correct! it took you %d tries\n", counter);
            return 0;
        }
    }
    printf("Invalid input\n");
    return 1;
}