Home > Article > Backend Development > Solving the problem of floating point calculation in C#
Let me show you a calculation problem to see your arithmetic ability.
0.1 +0.1 +0.1 - 0.3 equals what?
You may ask such a simple question, are you looking down on me? It must be equal to 0.
There is no problem if you calculate directly, but what if you use a computer?
The time to witness the miracle has arrived, look at the code:
void Main() { var f = 0.1 +0.1 +0.1 -0.3; Console.WriteLine("f=={0}",f); }
Running result:
This is because of the accuracy of the computer, the lack of accuracy in the internal storage and operation of the computer, etc. I may not be able to explain it clearly, but you can use the following solution. Solution:
void Main() { //var f = 0.1 +0.1 +0.1 -0.3; //Console.WriteLine("f=={0}",f); var f1 = new Decimal(0.1) + new Decimal(0.1) + new Decimal(0.1) - new Decimal(0.3); Console.WriteLine("f1 == {0}",f1); }
Running result:
This is the normal operation result.
La la la! ! ! !
The above is the detailed content of Solving the problem of floating point calculation in C#. For more information, please follow other related articles on the PHP Chinese website!