c - float 舍入问题

标签 c floating-point

我有以下源代码,但结果没有四舍五入到小数点后两位。

#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?

最佳答案

使用“%0.2f”代替 %f ,它将打印最多 2 位小数的值

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

关于c - float 舍入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45070669/

相关文章:

c - 使用 C 向 PNG 图像添加文本/注释

C 错误 : invalid operands of types 'int*' and 'unsigned int' to binary 'operator*' |

c++ - 最大可表示负 float

c - 为什么我的一个功能运行得这么慢?

c - `main.c' 需要错误 : make: *** No rule to make target `main.o' ,。停止

floating-point - 在什么范围内,整数算术加法和减法可以精确到 IEEE double 浮点中的整数?

python - Python 和一般情况下的浮点相等性

floating-point - 没有下溢和溢出,是否有任何2个数字,其中A < B为十进制形式,但转换为 float 后A> B?

c - 等待函数作为 while 循环条件

c - 动态内存分配以反向打印 float 数组