c - C中的猜谜游戏,无法获得有效的尝试次数,变量为 "counter"

标签 c

不太确定如何让计数器变量来计算猜对数字需要多少次尝试。我尝试过输入“counter++;”在每个 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;

}

最佳答案

只有当用户猜测正确时,您才会增加计数器。相反,您应该在每次尝试时增加它。

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

#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;
}

关于c - C中的猜谜游戏,无法获得有效的尝试次数,变量为 "counter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550155/

相关文章:

C 使用 strcpy 替换二维字符数组中的字符串问题

python - 如何从C共享库返回无符号字符数组来调用python函数

c - sizeof 操作数中的 VLA 和副作用

c - 如何在 C 中将值从整数数组传递到带有空格的字符串数组

完成循环的 c int 比较

c - 应用于字符串数组指针的逻辑

c++ - 代码::具有 MinGW 链接的 block 失败

c - 考虑到优先级和结合性,如何解决这个表达式?

C 缓冲区说明

c - 指针的作用类似于局部变量,并且不会在函数中保留其修改