gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:19:21 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com