C#通过简单的数学运算获得奇怪的结果 [英] C# Getting strange results for a simple math operations
问题描述
我注意到在添加两个双打时有一些奇怪的行为,有时它工作正确,有时却不正确!
I have noticed for some strange behavior while adding two doubles, sometimes it works correct, and sometimes not!
这里是第一个示例:
double num1 = 0.1 + 0.7; //Guess the result?
简单-0.8 !!!
Easy - 0.8 !!! or not?
看看奇怪的结果:
然后猜测,if语句在else块中并打印 num1
-不,它不打印0.799999999999993,它打印0.8。
And guess what, the if statement is going inside the else block, and prints the num1
- and no, it doesn't prints 0.799999999999993, it prints 0.8.
所以我走了进一步前进并尝试以下代码:
So I have gone one more step forward and tried this code:
if (0.1 + 0.7 == 0.8) //Returns false ??
{
Console.WriteLine("Correct");
}
好的,很奇怪,但是现在我找到了正确的方法,应该使用f (浮动)。我记得double有很多空格,所以它可以包含更大的数字,也许是原因。
OK, strange, but now I found the correct way, it should use f (float). As I remember double has many spaces, so it can contain higher numbers, maybe this is the cause.
float num2 = 0.1f + 0.7f;
if (num2 == 0.8f) //Perfect - finally works !!!
{
Console.WriteLine("Correct");
}
else
{
Console.WriteLine(num2);
}
但是现在,我尝试这样做-并再次返回false,为什么?
But now, I try this - and again it returns false, why?
if (0.1f + 0.7f == 0.8f) //Returns false :(
{
Console.WriteLine("Correct");
}
调试时手表的结果:
有人可以向我解释这里出什么问题吗?是那些错误吗?
Can someone explain me what's wrong here? Are those bugs?
预先感谢。
推荐答案
浮点运算并不精确,您应该阅读文章每位计算机科学家应了解的浮点运算法则。如果您希望计算精确到十进制,则应使用 十进制
类型,其中 0.1m + 0.7m == 0.8m
是 true
。您应注意,十进制
使用浮点数,就像 float
和 double
,但底数是10,而不是2。由于以2为底数的处理非常容易且经过高度优化,因此十进制
要慢得多。它也有其自身的不准确性,仅在处理可以用短小数位数表示的数字(例如 0.7
和 0.1
),使其更适合财务数据。
Floating point arithmetic is not precise. You should read the article What Every Computer Scientist Should Know About Floating-Point Arithmetic. If you want your calculations to be precise in a decimal sense, you should use the decimal
type, where 0.1m + 0.7m == 0.8m
is true
. You should note that decimal
uses floating point numbers just like float
and double
, except that the base is 10, not 2. Since dealing with base 2 is so much easier and highly-optimized, decimal
is much slower. It also has its own inaccuracies, it's only precise when dealing with numbers that can be represented in a short number of decimal digits (like 0.7
and 0.1
), making it good for financial data.
了解浮点数的另一篇有用的文章是维基百科的双精度浮点格式。
Another useful article to understand floating point numbers is Wikipedia's Double-precision floating-point format.
这篇关于C#通过简单的数学运算获得奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!