double Money::rounding(int convert, Currency m)
{
int tmp;
if ( (convert % m) > (m / 2.0)) {
tmp = convert + (m - (convert % m));
} else {
tmp = convert - (convert % m);
}
return convert / 100.0; // error happens here as well, 945 becomes 9.44
}
Money round(const Money target, Currency m)
{
int tmp;
double rounded;
if (target.amount < 0) {
tmp = -(target.amount * 100);
rounded = -Money::rounding(tmp, m);
} else {
tmp = target.amount * 100;
//error happens here
std::cout << tmp << std::endl; // ouput 944, should be 945
rounded = Money::rounding(tmp, m);
}
Money newM {0, 0};
newM.setAmount(rounded);
return newM;
}
int main(int argc, const char * argv[])
{
Money a {9, 45}; // equal 9.45
Money b = round(a, Currency::NICKLE); //argument a is 9.45
cout << b << endl;
}
该函数是将Money实例目标舍入到最接近的货币,在本例中为NICKLE。 因为货币a是9.45,它应该是9.45。但是在舍入之前的乘法中存在一个问题,tmp = target.amount * 100; &lt; - 变为944,但它应该是945,我知道舍入错误有时会发生,但这只会乘以100,为什么会出现舍入错误?
答案 0 :(得分:0)
在功能rounding
中定义tmp
,但不要使用它。
应该是
return tmp / 100.0;