浮动错误 [英] Float Error

查看:107
本文介绍了浮动错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(int)(0.04F * 100F)= 3 ??????为什么?

(int)(0.04F*100F) = 3 ????? WHY?

推荐答案

似乎使用浮点类型会导致精度降低,并且当结果值强制转换为int时,会将其四舍五入为最接近的整数.请注意以下内容:

float y = 0.04F * 100F;//4-在数学运算期间不进行强制转换就可以了.
int x = (int)y); //4-然后进行无问题投射

int x = (int)(0.04F * 100F);//3-如果在操作过程中进行投射,那简直是错误的

int x = Convert.ToInt32(0.04F * 100F);//4-使用ConvertTo会得到期望的答案,即使您将表达式作为参数输入(可能是因为在将表达式传递给ToInt32()方法之前已对表达式进行了求值.

int x = (int)(0.04 * 100);//4-隐式双打

int x = (int)(0.04M * 100M); //4-使用小数进行数学运算-更精确

int x = (int) 0.04D * 100D); //4-双打看起来不错

欢迎来到浮点数学的美好世界.
It appears that using a float type induces less precision, and when the resulting value is cast to an int, it rounds down to the nearest whole number. Note the following:

float y = 0.04F * 100F; // 4 - without casting DURING the math operation, it''s fine.
int x = (int)y); // 4 - and then it casts without issue

int x = (int)(0.04F * 100F); // 3 - if you cast during the operation, it''s just plain wrong

int x = Convert.ToInt32(0.04F * 100F); // 4 - using ConvertTo results in the expect answer, even if you put the expression in as the parameter (probably because the expression is evaluated before passing it to the ToInt32() method.

int x = (int)(0.04 * 100); // 4 - implicit doubles

int x = (int)(0.04M * 100M); // 4 - using decimal for the math - much more precise

int x = (int) 0.04D * 100D); // 4 - doubles seem to act fine

Welcome to the wonderful world of floating point math.


因为您可能会失去浮点数和整数之间的精度.浮点数旨在处理涉及非常大或非常小的数字的计算,但是这样做会损失精度,这要付出代价-多少取决于实际值.如果要精确计算,则应始终使用整数值.
Because you can lose precision between floating and integers. Floating point numbers are designed to handle calculations involving very large or very small numbers, but there is a cost in that precision will be lost - how much depends on the actual values. If you want precise answers to your calculations then you should always use integral values.


这篇关于浮动错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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