c++中,将float/double转换为int时损失1

C++, losing 1 when converting float/double to int?

本文关键字:int 损失 转换 double float c++      更新时间:2023-10-16

我想计算零钱,并将其转换为便士。

#include <iostream>
using namespace std;
int main()
{
    float cost   = 5.15,
          paid   = 10.00,
          change = 0.0;
    int pennies = 0.0;
    change = paid - cost;
    pennies = static_cast<int>(change * 100);
    cout << change << endl;       //4.85
    cout << pennies << endl;      //484  ??
    return 0;
}

penny的计算结果是484,我的penny去哪了?

我已经尝试过float和double,有和没有static_cast。

我在c++入门课上,所以重点是用基本的操作来做这些。

剂量(4.85 * 100)评价为484.999999…当使用浮点数时,它被截断了吗?

使用 .........................................................