2017-07-13 116 views
-1

我有以下源代码,但结果不是舍入到小数点后两位。四舍五入浮点数的问题

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <math.h> 

int main(int argc, char *argv[]) 
{ 
    float x1=0; 
    float x2 = 0; 
    float result=0; 
    x1 = 8961.650391; 

    result = x1 * 100 + 0.5; 
    result = (float)floor(result); 
    printf("Result = <%f>\n", result); 

    result = result/100; 
    x2 = result; 
    printf("x2 = <%f>\n", x2); 

    return 0; 
} 

请帮忙解决问题。

Result = <896165.000000> 
x2 = <8961.650391> 

如何获取x3 = 8961.650000?

回答

3

使用 “%0.2F”,而不是%f时,将打印值高达2小数

x2= roundf(result * 100)/100; 
printf("x2 = <%0.2f>\n", x2); 
+0

但我需要四舍五入的价值,所以我需要X2 = <8961.65> – user5240895

+0

添加了roundf功能,这将帮助你圆也。 ,查看更新后的答案 –

2

float通常可以代表约2 不同确切数字。
毕竟是typically encoded using 32-bits

8961.65不是其中之一。最接近的float到8961.65是8961.650390625f。下面显示了之前和之后的float

要打印float精确到0.01,建议使用"%.2f"以及@pritesh agrawal

建议与rint()round()四舍五入。

int main(void) { 
    float x = 8961.650391f; 
    float x100 = rint(x * 100.0); 
    float result = x100/100.0f; 

    printf("%f %.2f\n", nextafterf(x, 0), nextafterf(x, 0)); 
    printf("%f %.2f\n", x, x); 
    printf("%f %.2f\n", nextafterf(x, x * 2), nextafterf(x, x * 2)); 
    printf("%f %.2f\n", x100, x100); 
    printf("%f %.2f\n", result, result); 
    return 0; 
} 

输出

8961.649414 8961.65 
8961.650391 8961.65 
8961.651367 8961.65 
896165.000000 896165.00 
8961.650391 8961.65 

如何获得X3 = 8961.650000?

不能8961.650000精确值。到打印一个值,四舍五入到小数点后两位,然后是四个零,可以使用下面的值,但是它的位数是chicanery

printf("%.2f0000\n", 8961.650390625f); 
    // output 8961.650000 
+0

看到原因: – user5240895

+0

x3 = atof(“8961.65”); \t printf(“x3 =%f \ n”,x3); >> x3 = 8961.650391 – user5240895

+0

如何获取x3 = 8961.650000 – user5240895