2
double x = 9.29;
double y = 8.69;

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

这给了我 0.6 的差异,但我需要它作为 0.60(两位小数) 有人可以帮我解决这个问题吗?

4

3 回答 3

7

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

这可以使用

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

或者

printf("%.2f\n", diff);
于 2012-06-20T15:52:18.157 回答
2

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

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

如果您正在使用 C,请尝试以下操作:

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

precision函数确定要在插入操作中写入以表示浮点值的最大位数。所以,如果你执行这段代码,你会得到

0.60

如果你将 presision 设置为 3 你会得到

0.600
于 2012-06-20T16:18:34.253 回答
0

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

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

注意:balOwed[i] 是一个“双”类型的“数组”。它在一个 for 循环下。无论如何,这会给出类似“欠款:1234.00”的输出。但是,它只给出“余额欠款: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) 并且必须包含一个新库。但这也没有用。希望能帮助到你!

于 2018-10-01T09:56:34.240 回答