Solving the problem of floating point calculation in C#

黄舟
Release: 2017-09-20 11:05:18
Original
2056 people have browsed it

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);
}
Copy after login

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);
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template