【发布时间】:2015-09-09 00:38:11
【问题描述】:
我想检查用户输入是纯整数还是浮点数。我试图通过使用floor 和ceilf 并将这些值与函数中的原始x 值进行比较来做到这一点。但是,这似乎有点问题,因为对于某些数字(例如 5.5),当 floor(5.5)!=5.5 和 ceilf(5.5)!=5.5 时,函数会不断返回 0 而不是 1。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <stdbool.h>
int intchecker(float x)//in a separate file
{
if (floor(x)==x && ceilf(x)==x)
{
//printf("%f",floor(x));
return 0;
}
else {
return 1;
}
}
int main()
{
char line[] = " +----+----+----+----+----+----+----+----+----+----+---+";
char numbers[] = " 0 5 10 15 20 25 30 35 40 45 50";
float balls,slots;
int slot[9];
printf("==========================================================\nGalton Box Simulation Machine\n==========================================================\n");
printf("Enter the number of balls [5-100]: ");
scanf("%f",& balls);
if (balls>100 || balls<5){
printf("/nInput is not within the range. Please try again.");
}
else if (intchecker(balls)==1){
printf("/nInput is not an integer. Please try again.");
}
else {
printf(" This is an integer.");
//some more code here
}
}
我尝试将 intchecker 代码放在另一个项目中,这似乎可以正常工作,没有任何错误,这与之前的项目不同,当我使用 printf 语句检查 floor(x) 值是否正确时,它不断显示不同的答案,例如输入为 5.2 时为“-2.000000”。这是我的第二个项目的代码:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int main()
{
float x;
scanf("%f",&x);
if (floor(x)==x && ceilf(x)==x){
printf("Integer");
return 0;
}
else {
printf("Non-Integer");
return 1;
}
}
当第一个代码不能正常工作时,第二个代码怎么可能完美运行?我编写/调用函数的方式有问题吗?(我对函数比较陌生——到目前为止只接触了 2 周)
我在网上搜索并看到了很多检查输入是整数还是浮点数的答案,甚至在 stackoverflow.com 本身上,但我的愿望不是找到其他方法来检查输入是整数还是浮点数(如果我愿意的话要做到这一点,我可以用谷歌搜索,stackoverflow.com 上也有很多这样的问题),但是要理解 为什么 我的第一个代码不起作用,因为据我所知,如果没有当前面临的任何错误,它应该可以正常工作。
非常感谢任何帮助!:)
【问题讨论】:
-
如果您需要一个整数值,那么为什么要从输入中扫描
float?同样floorf(x) == x或ceilf(x) == x就足够了;你不需要两者。 -
“我使用 printf 语句检查 floor(x) 值是否正确,它一直显示不同的答案,例如当输入为 5.2 时显示“-2.000000”。”您需要显示表现出该行为的确切代码,因为您发布的代码中没有任何内容可以做到这一点。我最好的猜测是您的真实代码存在缓冲区溢出错误或其他未定义的行为。
-
您是否为两个程序提供完全相同的输入?
scanf("%f",&myfloat)的“5”实际上可能读入 5.0000000000000001,而“4”可能正好是 4.0。这一切都取决于 scanf() 的实现。 -
代码有趣地使用了
ceilf(float)和floor(double),但没有使用floorf(float)。我怀疑FLT_EVAL_METHOD是1 或2,而main()代码已优化为double。如果您使用floorf()编码,是否会出现差异?printf("%d\n", FLT_EVAL_METHOD);是什么? -
那么
main.c有int intchecker(float x);的原型吗?如果不是,那么这可能就是问题所在。