2014-09-30 68 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) ...