首页 > 解决方案 > 避免 Int 双重类型转换舍入?

问题描述

我通过将整数除以 10 的幂来将 an 转换int为 a 。对于具有 7 位或更大数字的整数,似乎在我将 an转换为 a时执行了舍入。为什么会发生这种情况,如何避免这种舍入?doubleintdouble

#include <iostream>
using namespace std;

double add_decimals(int x, int decimal_places)
{
    double ret = 1.0 * x;
    cout << "x= " << x << endl;
    cout << "ret before changes= " << ret << endl;
    for (int i = 0; i < decimal_places; ++i)
    {
        ret /= 10;
    }
    return ret;
}

int main() 
{
    double d = add_decimals(1234566, 2);
    cout << "d= " << d << endl;
}

标签: c++casting

解决方案


没有;您只是没有正确观察这些值。

快速解决:

std::cout << "d= " << std::fixed << d << endl;

您将需要#include <iomanip>使用std::fixed.


推荐阅读