c - C语言中的猜谜游戏
问题描述
我使用 while 循环在 C 编程中构建了一个猜谜游戏,但在执行过程中遇到了问题。因此,当我打印一个小于猜测数或大于猜测数的数字时,我会得到正确答案。但是当用户输入正确答案时,屏幕会显示更大数字的语句“您输入的数字大于密码”。然后它在“这是秘密号码”下方显示正确的声明。我认为问题可能是因为 else 语句没有定义更大数量的条件,但我不知道如何解决这个问题。有人可以帮助我吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess;
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}
解决方案
您认为问题可能是因为 else 语句没有定义更大数字的条件,所以您应该添加它。
guess
此外,您必须在使用其值之前进行初始化。
正确使用缩进格式化代码是另一个重要部分。
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess = !SecretNum; /* initialize guess : guess will be different value from SecretNum using this */
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else if (guess > SecretNum) /* add condition */
printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}
推荐阅读
- javascript - CSS 样式问题 - 未在 Firefox 中显示
- elasticsearch - elasticsearch混合映射动态对象
- python - Errno 32 带有 multiprocessing.Queue 的管道损坏错误
- spring - 如何使用 Swagger 生成 Spring Boot REST 客户端
- swift - 在 Swift 中添加两个键路径
- java - Java Jersey 如何以文件为参数上传文件
- email - 如何在gmail收件箱预览中显示图像
- vue.js - 如何在安装生命周期挂钩之前填充数组
- .htaccess - 如何从您的 URL 中删除所有 /page.html
- javascript - d3.js 文本未设置样式