在C ++中将double转换为int而不舍入错误 [英] Convert double to int in C++ without round down errors

查看:143
本文介绍了在C ++中将double转换为int而不舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将 double 转换为 int

  double dblValue = 7.30; 
int intValue =(int)(dblValue * 100); //我想intValue存储极端730;
cout<< intValue;
729

 我知道编译器读取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 an int:

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++ and casting 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆