写if语句来标识浮点变量是否包含小数位后面的值。
示例代码:
AAA = 123.456
if( AAA has value behind decimal = true)
{
printf("true")
}
// ...or user input changes value of AAA...
AAA = 123.000
if( AAA has value behind decimal = true)
{
printf("false")
}
任何帮助?
答案 0 :(得分:3)
#include <stdio.h>
#include <math.h>
int main(void)
{
double param, fractpart, intpart;
param = 123.456;
fractpart = modf(param , &intpart);
if (fractpart != 0.0) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
请注意,由于舍入错误和截断,计算过程中会出现数字错误,例如:
0.11 - (0.07 + 0.04) != 0.0
您可以控制这些舍入错误(根据您的比例调整EPSILON
值):
#include <stdio.h>
#include <math.h>
#define EPSILON 0.00000000001
int almost_zero(double x)
{
return fabs(x) < EPSILON;
}
int main(void)
{
double param, fractpart, intpart;
param = 0.11 - (0.07 + 0.04);
fractpart = modf(param , &intpart);
if (!almost_zero(fractpart)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
答案 1 :(得分:0)
您正在寻找fmod(AAA,1.0f)
答案 2 :(得分:0)
如果它适合长:if ((long) AAA == AAA) ...