Writing if statement to identify if float variable holds value behind decimal place.
写入if语句,以确定浮动变量是否具有小数点后的值。
Example code:
示例代码:
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")
}
Any help?
任何帮助吗?
3 个解决方案
#1
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;
}
Note that numerical errors arise during computations due to round-off errors and truncation, e.g.:
注意,由于舍入误差和截断,在计算过程中出现了数值误差。
0.11 - (0.07 + 0.04) != 0.0
You can control those round-off errors (adjust the EPSILON
value according your scale):
您可以控制这些舍入错误(根据您的比例调整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;
}
#2
0
You're looking for fmod(AAA,1.0f)
你正在寻找作用(AAA,1.0度)
#3
0
If it fits in a long: if ((long) AAA == AAA) ...
如果它适合长时间:If ((long) AAA == AAA)……
#1
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;
}
Note that numerical errors arise during computations due to round-off errors and truncation, e.g.:
注意,由于舍入误差和截断,在计算过程中出现了数值误差。
0.11 - (0.07 + 0.04) != 0.0
You can control those round-off errors (adjust the EPSILON
value according your scale):
您可以控制这些舍入错误(根据您的比例调整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;
}
#2
0
You're looking for fmod(AAA,1.0f)
你正在寻找作用(AAA,1.0度)
#3
0
If it fits in a long: if ((long) AAA == AAA) ...
如果它适合长时间:If ((long) AAA == AAA)……