四舍五入小数点后两位

时间:2012-06-20 15:44:48

标签: c++ rounding

double x = 9.29;
double y = 8.69;

double diff = floor((x - y)*100+0.5)/100.0;

这给了我差异0.6但我需要它为0.60(两个小数点) 有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:7)

double的值是0.6,因为0.6和0.60(数学上)是相同的。您需要的是在打印值时设置精度,而不是在计算时。

这可以使用

完成
cout << setprecision (2) << diff << endl;

printf("%.2f\n", diff);

答案 1 :(得分:2)

如果你使用的是C ++,你应该这样做:

cout.precision(2);
cout << fixed << diff << "\n";

如果你正在使用C,那么试试这个:

printf("%.2e\n", diff);

precision函数确定在插入操作上写入的最大位数,以表示浮点值。因此,如果您执行此代码,您将获得

0.60

如果你将presision设置为3,你将获得

0.600

答案 2 :(得分:0)

我尝试了解决方案,但对我来说效果并不理想。我有这样的东西。

 cout << "balance owing: " << balOwed[i] << endl;

注意:balOwed [i]是类型为'double'的'array'。它处于for循环之下。无论如何, 这将给出类似“余额欠款:1234.00”的输出。但是,它只给出“ Balance owing:1234”之类的输出。

我尝试使用:

  cout.presicion(2);
  cout << "balance owing: " << balOwed[i] << endl;

它没有用。所以最终对我有用的是以下代码:

  cout.setf(ios::fixed);
  cout.precision(2);
  cout << "balance owing: " << balOwed[i] << endl; 

为了让大家知道,我还尝试了setprecision(2)并不得不包含一个新库。但这也不起作用。希望对您有帮助!