为什么我的号码被错误地舍入? [英] Why is my number being rounded incorrectly?

查看:123
本文介绍了为什么我的号码被错误地舍入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这感觉就像那种只能在原地失败的代码,但我会尝试将它调整成代表我所看到的代码片段。

  float f = myFloat * myConstInt; / *其中myFloat == 13.45,myConstInt == 20 * / 
int i =(int)f;
int i2 =(int)(myFloat * myConstInt);

完成代码后,i == 269和i2 == 268。这里有什么事情来解决这个问题呢?

解决方案

但是,只要你将它存储在浮点f中,那么额外的精度就会丢失。在第二种方法中,你不会失去这种精度,当然,直到你将结果转换为int。


$ b 编辑:看到这个问题为更好的解释比我可能提供的。


This feels like the kind of code that only fails in-situ, but I will attempt to adapt it into a code snippet that represents what I'm seeing.

float f = myFloat * myConstInt; /* Where myFloat==13.45, and myConstInt==20 */
int i = (int)f;
int i2 = (int)(myFloat * myConstInt);

After stepping through the code, i==269, and i2==268. What's going on here to account for the difference?

解决方案

Float math can be performed at higher precision than advertised. But as soon as you store it in float f, that extra precision is lost. You're not losing that precision in the second method until, of course, you cast the result down to int.

Edit: See this question Why differs floating-point precision in C# when separated by parantheses and when separated by statements? for a better explanation than I probably provided.

这篇关于为什么我的号码被错误地舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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