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”输出等于第一次和第二次的总和。如何解决问题?
例如,
第一次:9 次尝试
第 2 次: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)
在进入-loop之前设置tries
为:0
while
num = rand() % 1000 + 1;
tries = 0;
while(guess != num)
推荐阅读
- python - 为什么在我的代码中 numba 比纯 python 慢?
- validation - 我必须将自定义对象客户的验证规则编写为
- reactjs - 根据路由改变导航 React 路由器
- javascript - 如何遍历以下充满图像的目录并将图像添加到我的 HTML 页面
- prolog - 如何在一系列数字上测试谓词并返回通过 Prolog 的那些
- python - 删除默认帮助命令
- r - 如何从多个回归模型中提取置信区间?
- html - 从 Wordpress 的主菜单中删除项目符号
- javascript - 什么时候虚拟 DOM 比真实 DOM 快?
- python - 将 href 添加到 panda .read_html DF