c程序在循环程序时重复游戏的尝试

标签 c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int num;
    int guess = 0;
    int response = 1;
    int tries = 0;
    srand(time(0));

    while (response == 1)
    {
        printf("Please type your first guess.\n");
        num = rand() % 1000 + 1;
        while (guess != num)
        {
            scanf("%d", &guess);
            tries = tries + 1;
            if (guess == num)
            {
                printf("good job\n");
            }
            else if (guess > num)
            {
                printf("too high, try again\n");
            }
            else
            {
                printf("too low, try again\n");
            }
        }
        printf("Guess Taken = %d\n", tries);
        printf ("Would you like to play again? \n");
        printf("Please type ( 1=yes, 2=no ) ");
        scanf ("%d", &response);


    }
    system("pause");
    return 0;
}

第二次运行程序“Guess Taken”的输出等于第一次和第二次的总和。如何解决问题?

例如,

第 1 次:9 次尝试

第二:8 次尝试

程序的输出显示了 17 次尝试而不是 8 次尝试。

最佳答案

 printf("I have a number between 1 and 1000.\n" 
     "Can you guess my number?\n" 
     "Please type your first guess.\n");
num = rand() % 1000 + 1; 
while(guess != num)

在进入 while 循环之前将 tries 设置为 0:

num = rand() % 1000 + 1;
tries = 0;
while(guess != num)

关于c程序在循环程序时重复游戏的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52503517/

相关文章:

c++ - 如何一起使用c和c++

c - 杀死除系统进程和我自己的进程之外的所有进程

c - 未父窗口无法设置HMENU ID?

c - 共享一个缓冲区——线程安全

c - memcmp 返回值的大小是什么意思?

c - 为什么巴塞尔问题总是显示相同的数字?

c - 通过 C 中的几个函数传递结构?

c - 阻止 Keil uvision 在函数调用时推送寄存器

c - C 中将正值四舍五入到小数点后 2 位

c - 使用 select() 监听多个客户端(TCP)