Solution of floating-point calculation problem in C #

Source: Internet
Author: User
Let 's look at a computational question and look at the arithmetic abilities of everyone.

0.1 +0.1 +0.1-0.3 equals a few?

People may say such a simple question, is not despise me? Must be equal to 0.

If the direct calculation is not a problem, but if you use a computer?

The time to witness a miracle is here, look at the code:


void Main () {    var f = 0.1 +0.1 +0.1-0.3;    Console.WriteLine ("F=={0}", f);}

Operation Result:

This is because of the problem of computer accuracy, in the computer's internal storage and operation of the lack of precision, and so on, I may not understand the explanation, however, you can use the following 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);}

Operation Result:

This is the result of the normal operation.

La La la!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.