四舍五入小数点后两位

Cam*_*mAd 2 c++ rounding

double x = 9.29;
double y = 8.69;

double diff = floor((x - y)*100+0.5)/100.0;
Run Code Online (Sandbox Code Playgroud)

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

tim*_*mos 7

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

这可以使用

cout << setprecision (2) << diff << endl;
Run Code Online (Sandbox Code Playgroud)

要么

printf("%.2f\n", diff);
Run Code Online (Sandbox Code Playgroud)