C#浮错误? 0.1 - 0.1 = 1.490116E-08 [英] C# float bug? 0.1 - 0.1 = 1.490116E-08

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

问题描述

这是怎么回事? 0.1 - 直到我得到0.1减法工作正常。我在Visual C#2008中使用nonoba.com API。

  Console.WriteLine(打!+用户[targetNum] .character.health +:+ player.character.profile.attackPower);用户[targetNum] .character.health  -  = player.character.profile.attackPower;Console.WriteLine(!健康+用户[targetNum] .character.health);

输出:

 打了! 0.1:0.1
健康! 1.490116E-08

感谢所有 - 我可能会使用十进制类型,因为我通常加/减漂亮的圆的数字。现在我只是去:

 如果(用户[targetNum] .character.health< = 0.00001)

这是我知道这是不是真的要在C#中的错误的方式 - 我以为它会无论是在我的code或错误一些缺乏了解,这是

看了所有建议的阅读,我将得出结论,我的愚蠢是因为正常使用ActionScript号码类型,这可能有小数点,而不是二进制浮点 - 无论如何,它绝不会放弃这个输出


解决方案

这似乎是pretty正常的浮点运算......你总是要核对一个小三角洲占潜移默化的四舍五入差异。根据不同的场景中,小数可能是你想要的东西。

基本上,除非你可以肯定,这是的究竟在这两种情况下相同的0.1(即什么也没有做他们),你是不是有可能获得零;一般来说,你会得到的东西非常接近为零。随着小数你通常会得到更多你所期望的直觉。

又见乔恩斯基特的网页位置:

What's going on?! Subtraction works fine until I get to 0.1 - 0.1. I'm in visual c# 2008 using the nonoba.com API.

Console.WriteLine("hit! " + Users[targetNum].character.health + " : " + player.character.profile.attackPower);

Users[targetNum].character.health -= player.character.profile.attackPower;

Console.WriteLine("health! " + Users[targetNum].character.health);

output:

hit! 0.1 : 0.1
health! 1.490116E-08

Thanks all - I might use the decimal type, as I'm normally adding/subtracting nice "round" numbers. For now I'll just go with:

if (Users[targetNum].character.health <= 0.00001)

By the way I knew this wasn't really going to be a "bug" in c# - I thought it would either by a bug in my code or some lack of understanding, which it was.

Having read all the recommended reading, I'm going to conclude that my folly was due to normally using the ActionScript Number type, which maybe has a decimal rather than binary floating point - anyway, it would never give this output.

解决方案

That seems pretty normal for floating point math... you always have to check against a small delta to account for imperceptible rounding differences. Depending on the scenario, decimal might be what you want.

Basically, unless you can be sure that it is exactly the same 0.1 in both cases (i.e. nothing has been done to them), you aren't likely to get zero; in general you'll get something very nearly zero. With decimal you'll usually get more what you expect intuitively.

See also Jon Skeet's pages here:

这篇关于C#浮错误? 0.1 - 0.1 = 1.490116E-08的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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