2014-09-30 31 views
-1

编写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

它是C语言吗? – 2014-09-30 07:22:23

回答

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; 
} 
0

如果它适合很长时间:if ((long) AAA == AAA) ...