在C ++中将double转换为int而不舍入错误 [英] Convert double to int in C++ without round down errors
问题描述
我有以下代码将 double
转换为 int
:
double dblValue = 7.30;
729
int intValue =(int)(dblValue * 100); //我想intValue存储极端730;
cout<< intValue;
我知道编译器读取dblValue为7.2999999,然后将它转换为int。
我的问题是:可以通过防止舍入错误?
如果你的解决方案避免使用C ++ 11或其他预定义的函数,这将是最好的。我使用的唯一的预处理器指令是
< iostream>
。解决方案在将不是整数(数学意义上的)的数字转换为整数时,不能防止舍入错误,唯一可以做的是尝试实现正确的舍入。
实现一个明智的(虽然不是完美的)四舍五入的最简单的方法如下:
int intValue =(int)(dblValue <0≤dblValue-0.5:dblValue + 0.5);
当然,因为你的问题被标记为
c ++
和铸造
我无法阻止用c ++风格的cast替换你的c风格的cast:int intValue = static_cast< int>(dblValue< 0?dblValue-0.5:dblValue + 0.5);
I have the following codes to cast a
double
into anint
:double dblValue = 7.30; int intValue = (int)(dblValue*100); //I want intValue to store extactly 730; cout << intValue;
Output:
729
I know that the compiler is reading dblValue as 7.2999999 before casting it to int.
My question is: Is it possible to cast it as 730 by preventing the round down errors?
It would be best if your solution avoid using C++11 or other predefined functions. The only pre-processor directive I am using here is
<iostream>
.解决方案You cannot prevent rounding errors when converting a number that is not an integer (in the mathematical sense) to an integer, the only thing you can do is try to achieve proper rounding.
The easiest way to achieve a sensible (although not perfect) rounding this is the following:
int intValue = (int)(dblValue < 0 ? dblValue - 0.5 : dblValue + 0.5);
And of course, since your question is tagged both
c++
andcasting
I cannot resist replacing your c-style cast with a c++ style cast:int intValue = static_cast<int>(dblValue < 0 ? dblValue - 0.5 : dblValue + 0.5);
这篇关于在C ++中将double转换为int而不舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!