用C++将双精度舍入到小数点后两位,但结果与预期不一样



我想计算给定价格的下限(2.65*0.9(

2.65 * (1 - 0.1) = 2.385

然后四舍五入到小数点后2位,结果为2.385->2.39

round(2.385) = 2.39

但是当我使用C++来实现以上内容时:

double pclose = 2.65;
double range = 0.1;
double lmtdown = pclose * (1 - range);
double lmtdownAfterRound= std::round( lmtdown * 100 ) / 100;
printf("pclose=%.2f, range=%.2f, limit down before round=%f,n", pclose, range, lmtdown);
printf("limit after round=%fn", lmtdownAfterRound);

但打印的结果是2.38!!!!!!我想要的不是2.39

pclose=2.65, range=0.10, limit down before round=2.385000,
limit after round=2.380000

我用std::floor:尝试了另一种更全面的方法

lmtdownAfterRound= std::floor(lmtdown * 100 + 0.5) / 100;
printf("limit after round =%fn", lmtdownAfterRound);

结果仍然是2.38:

limit after round with floor=2.380000

我的c++代码有问题吗?如何获得正确的舍入值

使用std::ceil/std::floor

工作代码

// Example program
// Example program
#include <iostream>
#include <cmath>
int main() {
double pclose = 2.65;
double range = 0.1;
double lmtdown = pclose * (1.0 - range);
int left = int(lmtdown *1000) %10;
double lmtdownAfterRound;
if (left >=5)
lmtdownAfterRound=std::ceil( lmtdown *100.  )/100.;
else
lmtdownAfterRound=std::floor( lmtdown *100.  )/100.;
printf("pclose=%.2lf, range=%.2lf, limit down before round=%lf,n", pclose, range, lmtdown);
printf("limit after round=%lfn", lmtdownAfterRound);
}

输出:

pclose=2.65, range=0.10, limit down before round=2.385000,
limit after round=2.390000

在此处进行测试:http://cppshell.com/

相关内容

  • 没有找到相关文章

最新更新