将float转换为int时的奇怪行为
Strange bahavior when converting float to int
我有一个类读取csv文件,其中包含小数点后不超过两位数字的数字记录。
int ReadCellWithFloat(int cellNumber, int multiplier) throw (FSByFieldException)
{
GoToCell( cellNumber );
float number;
FileStream >> number;
std::cout << "what we've got: " << number;
if ( !FileStream.good() )
{
throw BuildException( FSByFieldException::NOT_FLOAT );
}
while ( multiplier-- )
{
number *= 10;
}
std::cout << ' ' << number << ' ' << (int) number << std::endl;
PassCell(); // here meaning pass comma separator
return (int) number;
}
对于包含浮点数"8.49"的单元格,输出结果如下:
what we've got: 8.49 849 848
为什么849在转换为整数时变成848,如何修复它?
849变为848,因为纯强制转换只是截断值。所以(int) 4.8
== 4。你可能会认为8.49 * 10 * 10
是849,但这并不一定是真的:)它就像架构所能表示的那样接近849,内部可能是848.999999…截断后为848。
要解决这个问题,您可以使用(int) round(number)
,您可能也有兴趣看看ceil()
和floor()
函数,以及关于浮点精度问题的一般信息,以避免在数字比较和诸如此类的问题上遇到麻烦。
这是因为浮点数在二进制空间中的存储方式。这个链接将向您展示8.49的值最好表示为浮点数8.4899997。
因此,当您将float类型强制转换为int类型时,它将解析float的实际值,而不是四舍五入的值。
有几种方法可以解决这个问题:1)使用双精度(这将减轻这个问题,而不是消除它)2)使用数学库将数字848.99四舍五入。
数字8.49
不能精确表示,所以当你将它乘以10
两次时,你最终会得到更像848.99999
的东西,当我尝试这个:
number = 8.49 ;
number *= 10 ;
number *= 10 ;
std::cout << std::fixed << number << std::endl ;
我得到848.999939
,当你cast
到integer
它被截断,所以你最终得到848
。使用roundf
将得到您想要的结果:
std::cout << std::fixed << roundf(number) << std::endl ;
在c++ 11中你只需要使用round
相关文章:
- 没有从阵列<float>到阵列<int>的可行转换
- 为什么我会收到此错误?无法将 {lb, ub} 从<大括号括起来的初始值设定项列表>转换为 float(**)(float*, int)
- 如何将 qml 的文本转换为 float 和 int
- 有没有比static_cast更优雅的从int到float的演员阵容<float>?
- 如何在函数中将字符串和分数存储为(Int 或 float)
- 谷歌测试编译错误 Os X:函数式转换从"int"到"internal::FloatingEq2Matcher"的模糊转换<float>
- 如何使用 std:from_chars 在 C++17 中从字符串转换为 int/float
- 如何修复 E2015 "ambiguity between pow(double,double) and pow(float,int)"
- C++优化从 int 到 float 的数组转换
- 如何在 c++ 中将数据从文件读取到 int/float 值
- 错误:二进制'operator*' 'int [1]'和'float'类型的操作数无效
- 功能使用INT和Float类型作为C 中的参数过载
- 内部字符串/字符如何在 int 和 float 中存储
- 无法将'int*'转换为参数'1'的'float*'
- 将 python list 作为 'float*' 或 'int*' 传递给 C/C++
- 在C++/Visual Studio中,通过给定数据格式(doubles、float、int、1位bools)的UDP发
- 当float转换为int时,此代码中是如何/为什么进行缩小的
- C++ 将字符串转换为 16 位无符号/有符号的 int/float
- C++:int*/float*到char*,为什么使用repret_cast会得到不同的结果
- 如何在等待用户输入int, float或其他类型时拒绝输入char/string