C++ 四舍五入两位小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11123213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rounding off double two decimal points
提问by CamAd
double x = 9.29;
double y = 8.69;
double diff = floor((x - y)*100+0.5)/100.0;
this gives me diff as 0.6 but I need it as 0.60 (two decimal points) Could someone please help me with this?
这给了我 0.6 的差异,但我需要它作为 0.60(两个小数点)有人可以帮我吗?
回答by timos
the value of the double is 0.6, because 0.6 and 0.60 are (mathematically) the same thing. What you need is to set the precision when you are printingthe value not when you are calculating it.
double 的值是 0.6,因为 0.6 和 0.60(在数学上)是相同的。您需要的是在打印值时而不是在计算值时设置精度。
This can be done using
这可以使用
cout << setprecision (2) << diff << endl;
or
或者
printf("%.2f\n", diff);
回答by Rontogiannis Aristofanis
If you are using C++ you should do something like that:
如果您使用的是 C++,则应该执行以下操作:
cout.precision(2);
cout << fixed << diff << "\n";
If you ere using C then try this:
如果您使用的是 C,请尝试以下操作:
printf("%.2e\n", diff);
The precision
function determines the maximum number of digits to be written on insertion operations to express floating-point values. So, if you execute this code you will get
该precision
函数确定要在插入操作中写入以表达浮点值的最大位数。所以,如果你执行这段代码,你会得到
0.60
and if you set the presision to 3 you will get
如果你将压力设置为 3 你会得到
0.600
回答by Aadn
I tried the solutions but it didn't quite work out for me. I had something like this.
我尝试了解决方案,但对我来说并不完全有效。我有这样的事情。
cout << "balance owing: " << balOwed[i] << endl;
NOTE: balOwed[i] is an 'array' of type 'double'. It was under a for loop. Anyway, this would give an output like "Balance owing: 1234.00". However, it was only giving output like "Balance owing: 1234".
注意:balOwed[i] 是一个“double”类型的“array”。它在 for 循环下。无论如何,这将给出类似“欠款余额:1234.00”的输出。但是,它只提供“余额欠款:1234”之类的输出。
I tried using:
我尝试使用:
cout.presicion(2);
cout << "balance owing: " << balOwed[i] << endl;
it didn't work. So what did finally work for me was the following code:
它没有用。所以最终对我有用的是以下代码:
cout.setf(ios::fixed);
cout.precision(2);
cout << "balance owing: " << balOwed[i] << endl;
Just to let you guys know, I also tried setprecision(2) and had to include a new library. But that didn't work either. Hope it helps!
只是为了让你们知道,我还尝试了 setprecision(2) 并且必须包含一个新库。但这也不起作用。希望能帮助到你!