c - 为什么我的 C 程序在不同的编译器中给出不同的输出?
问题描述
我的程序的结果不是我所期望的,并且在不同的编译器上是不同的。
我已经在三个编译器上进行了尝试,其中两个给出了相同的结果。但我想要两个结果的组合。
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int iRandomNum = 0;
int iUserInput = 0;
const int VIP = 7;
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 to 10.\n Make a wish and type in the number.\n");
scanf("%d", &iUserInput);
if(isdigit(iUserInput))
{
printf("\n\nYou did not enter a digit between 1 to 10.\n\n");
}
else
{
if(iUserInput==iRandomNum || iUserInput==VIP)
printf("\n\nYou guessed it right!\n\n\n");
else
printf("\n\nSorry the right answer was %d.\n\n\n", iRandomNum);
}
return 0;
}
当我选择任何数字时,如果我在这个猜数字游戏中没有选择正确的数字,程序只会提醒我。但是在 7 的情况下,我们总是有正确的答案。这发生在两个在线编译器中。但是在铿锵声中,当我这样做时,它不起作用。然后 isdigit 函数不起作用
解决方案
使用%d
格式说明符,您正在读取int
into iUserInput
。那是正确的,但是您使用它isdigit
来尝试查看数字是否在1
和之间10
。但是,此函数用于确定 achar
是否在'0'
和之间'9'
。这不一样 - 假设 ASCII 这些字符分别等于48
和57
。因此,您isdigit
很可能会检查输入的数字是否介于48
和之间57
(尽管不能保证使用 ASCII,因此不同的编码可能会导致不同的结果)。
相反,检查应该是:
if((iUserInput >= 1) && (iUserInput <= 10)) {...}
推荐阅读
- java - 使用命令行执行 Java 类文件,但来自“错误”目录
- java - 在android studio中制作带有用户详细信息的证书
- javascript - 如何使整个 div 可点击(进入链接)?
- sequelize.js - 在续集中使用 [Op.and] 准备动态 where
- javascript - 如何在 Spring Boot 的所有 JSP 页面中显示相同的城市名称?
- odata - ODATA - 带有 AND 和开头的 OR 运算符
- java - 登录操作上的奇怪帖子字符串;黑客尝试?
- python - 如何在熊猫列中创建单词的二进制表示?
- algorithm - 给定一个数字列表,找到所需的最小交换次数,以便没有两个相邻元素相同
- javascript - 警告:测试中 Slider 的更新未包含在 act(...) 中