Home  >  Article  >  Backend Development  >  Solving the problem of floating point calculation in C#

Solving the problem of floating point calculation in C#

黄舟
黄舟Original
2017-09-20 11:05:182067browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn