从数学C++中获得美分

Getting Cents from Math C++

本文关键字:C++      更新时间:2023-10-16

现在,我的代码的工作原理是,当我打印出美分时,由于编译器所做的舍入错误,比如0.95*100,它会给我94或不是95的东西。我知道数学是如何正常计算的,但有了这个舍入误差,我做不到。

也不用担心问我为什么同时使用C和C++。因为这是我的教练想要的。

这是相关代码。

if (dollarAmount < 10.00 && dollarAmount >= 1.00)
{
    cents = (dollarAmount - static_cast<int>(dollarAmount)) * 100;
    digit = (((static_cast<int>(dollarAmount)/ 1)));
    strcat(amountInWords, lookUp[digit]);
    strcat(amountInWords, " dollars and ");
}

整个项目代码:https://gist.github.com/anonymous/65c052277c67f03de643

当舍入很重要时,不要使用浮点变量。只需使用一个长变量来存储美分。

使用round()而不是static_cast<int>。实际值和浮点数之间的差值是0.0000000左右。四舍五入总是能给出正确的答案。

此外,仅在乘以100之后对进行舍入。

相关文章:
  • 没有找到相关文章