我有以下源代码,但结果没有四舍五入到小数点后两位。
#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/