c - for循环中的计数器不能通过增加2来正常工作
问题描述
我正在做一个非常基本的 C 作业。我需要制作一个游戏,让计算机生成一个随机数并让用户尝试猜测它。用户有 5 次尝试,我试图通过 for 循环给出。但是在每个循环上,尝试减少 2 而不是 1。我无法找出我在这里缺少的东西。我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int counter;
int prediction;
int number;
srand(time(NULL));
number = 1 + (rand() % 100);
for ( counter=1; counter<=5; counter++ ) {
printf("\nGuess my number from 1 to 100: \n");
scanf("%d", &prediction);
if (prediction < number) {
printf("My number is greater than your guess. \n");
printf("You have %d attempts left \n", (5-counter) );
counter++;
}
if (prediction > number) {
printf("My number is smaller than your prediction. \n");
printf("You have %d attempts left \n", (5-counter) );
counter++;
}
if (prediction == number) {
printf("Congratulations! You guessed my number correctly! \n");
break;
}
}
return 0;
}
解决方案
您将计数器增加两次:一次在两个if
块中,一次在for
循环线本身。删除循环体中的额外增量:
if (prediction < number) {
printf("My number is greater than your guess. \n");
printf("You have %d attempts left \n", (5-counter) );
}
if (prediction > number) {
printf("My number is smaller than your prediction. \n");
printf("You have %d attempts left \n", (5-counter) );
}
推荐阅读
- c# - 调试在 VS Mac 中不起作用 - Blazor Web 应用
- javascript - Vue.js - 无法访问模板中对象中的值
- squarespace - 更改默认显示价格
- r - Minimal Bookdown 添加了 jpg 参考而不是渲染图像
- arrays - 当我尝试用数组填充二进制文件时,它总是为空
- node.js - 在 Electron 中使用 Node.js Crypto:crypto.scryptSync 不是函数
- javascript - 在来自客户端视频源的单个帧上运行 python 脚本
- c# - Unity - 如何同时运行 2 个不同的 IEnumerator 方法?
- javascript - 以 JSON 格式显示 CouchDB 的文档
- bash - 使用 ccrypt 附加加密文件?