c++ - 避免 Int 双重类型转换舍入?
问题描述
我通过将整数除以 10 的幂来将 an 转换int
为 a 。对于具有 7 位或更大数字的整数,似乎在我将 an转换为 a时执行了舍入。为什么会发生这种情况,如何避免这种舍入?double
int
double
#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;
}
解决方案
没有;您只是没有正确观察这些值。
快速解决:
std::cout << "d= " << std::fixed << d << endl;
您将需要#include <iomanip>
使用std::fixed
.
推荐阅读
- google-apps-script - 如何使用 Apps 脚本将多个电子表格中特定列的数据导入到一个电子表格中?
- swift - 从 SF Symbols 字体创建一个不同颜色的 SKSpriteNode
- python - Python 和虚拟环境的问题,Windows 10 上的初学者程序员
- amazon-web-services - 为什么我的 AWS RDS 备份的保留时间比配置的长?
- ios - 带有 adMob 的 Xcode 项目,项目设置不包括 macCatalyst 的 adMob,Clang 链接器错误
- jersey - Restlet 和 Jersey 并存?
- ios - 以编程方式在 Swift 中设置标签颜色
- python - Beautiful Soup 标签行为异常
- c# - 如何将 JsonPatchDocument 作为属性传递给发布对象?
- java - 您将如何实施正确的 https 客户端身份验证