圆形浮点:在小数点四舍五入到最接近的小数位后正好打印两位数

时间:2021-10-21 17:08:46

How do we round a floating point number in C/C++ to print exactly two digits after the decimal point rounded to the nearest decimal place? say for example,when I use,

我们如何在C / C ++中舍入浮点数以在小数点四舍五入到最接近的小数位后正好打印两位数?例如,当我使用时,

printf("%.2f", 12.555);
cout<<fixed<<setprecision(2)<<12.555<<endl;

I get,

12.55
12.55

but I need output as,

但我需要输出,

12.56
12.56

2 个解决方案

#1


1  

C or C++ don't care about what you need.

C或C ++不关心你需要什么。

12.555 is not a binary floating point number. Binary floating point numbers are all integers multiplied by or divided by a power of two. 12.555 is not such a number. So when you write 12.555 then what you get is the floating-point number nearest to 12.555. Which may be smaller or larger than 12.555 and will be correctly rounded to 12.55 or correctly rounded to 12.56.

12.555不是二进制浮点数。二进制浮点数是所有整数乘以或除以2的幂。 12.555不是这样的数字。所以当你写12.555时,你得到的是最接近12.555的浮点数。它可能小于或大于12.555,并将正确舍入到12.55或正确舍入到12.56。

Calculate x * 1000 and round (x * 1000), which will give 12555. If x * 1000 is very close to round (x * 1000) and the last digit of round (x * 1000) is odd then increase it by 1. Divide by 10, round again, divide by 100.

计算x * 1000和round(x * 1000),这将给出12555.如果x * 1000非常接近round(x * 1000)并且round(x * 1000)的最后一位数是奇数,则将其增加1。再除以10,然后再除以100。

#2


4  

The problem is that the actual double value for 12.555 is

问题是12.555的实际双精度值是

12.55499999999999971578290569595992565155029296875000

so when you round it to 2 decimal places it rounds down to 12.55. There's really nothing you can do about that.

因此当你将它四舍五入到小数点后两位时,它会向下舍入到12.55。你真的无能为力。

#1


1  

C or C++ don't care about what you need.

C或C ++不关心你需要什么。

12.555 is not a binary floating point number. Binary floating point numbers are all integers multiplied by or divided by a power of two. 12.555 is not such a number. So when you write 12.555 then what you get is the floating-point number nearest to 12.555. Which may be smaller or larger than 12.555 and will be correctly rounded to 12.55 or correctly rounded to 12.56.

12.555不是二进制浮点数。二进制浮点数是所有整数乘以或除以2的幂。 12.555不是这样的数字。所以当你写12.555时,你得到的是最接近12.555的浮点数。它可能小于或大于12.555,并将正确舍入到12.55或正确舍入到12.56。

Calculate x * 1000 and round (x * 1000), which will give 12555. If x * 1000 is very close to round (x * 1000) and the last digit of round (x * 1000) is odd then increase it by 1. Divide by 10, round again, divide by 100.

计算x * 1000和round(x * 1000),这将给出12555.如果x * 1000非常接近round(x * 1000)并且round(x * 1000)的最后一位数是奇数,则将其增加1。再除以10,然后再除以100。

#2


4  

The problem is that the actual double value for 12.555 is

问题是12.555的实际双精度值是

12.55499999999999971578290569595992565155029296875000

so when you round it to 2 decimal places it rounds down to 12.55. There's really nothing you can do about that.

因此当你将它四舍五入到小数点后两位时,它会向下舍入到12.55。你真的无能为力。