如何将浮点值转换为精确精度如123.3443到1233443的整数? [英] How to convert floating value to integer with exact precision like 123.3443 to 1233443?

查看:68
本文介绍了如何将浮点值转换为精确精度如123.3443到1233443的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

int main() {
  float f = 123.542;
  int i = (int)f;
  printf("%d\n",i);
}

推荐答案

123.3443不能用浮点数精确表示-在32位浮点数中,它有效地表示为 16166984/131072 ,实际上是123.34429931640625,而不是123.3443.(大约有6.8 x 10 ^ -7.)

123.3443 can't be exactly represented by a floating-point number -- in a 32-bit float, it's effectively represented as 16166984 / 131072, which is actually 123.34429931640625, not 123.3443. (It's off by around 6.8 x 10^-7.)

如果这确实是您想要的结果(可能不是),请查看IEEE-754浮点运算的工作原理,并提取您喜欢的任意精度数学套件.一旦了解了幕后"的情况,生成精确的表示就不会太困难了.生成足够接近"的舍入表示实际上要困难得多.:)

If this is really the result you want (which it's probably not), take a look at how IEEE-754 floats work, and pull out your favorite arbitrary-precision math suite. Once you understand what's going on "behind the scenes", generating an exact representation shouldn't be too hard. Generating a "close enough" rounded representation is actually much harder. :)

这篇关于如何将浮点值转换为精确精度如123.3443到1233443的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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