首页 > 解决方案 > 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”输出等于第一次和第二次的总和。如何解决问题?

例如,

第一次:9 次尝试

第 2 次:8 次尝试

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

标签: c

解决方案


 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)

在进入-loop之前设置tries为:0while

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

推荐阅读