Comparison of double and float values

Source: Internet
Author: User

First, let's look at the two programs on geeksforgeeks:

Procedure 1:

 
# Include <stdio. h> int main () {float x = 0.1; If (x = 0.1) printf ("if"); else if (x = 0.1f) printf ("else if"); else printf ("else ");}

Procedure 2:

 
# Include <stdio. h> int main () {float x = 0.5; If (x = 0.5) printf ("if"); else if (x = 0.5f) printf ("else if"); else printf ("else"); System ("pause"); Return 0 ;}

The output of program 1 is else if, while that of Program 2 is: if

Why?

This is because the precision of double and float is different. If the decimal point is converted to binary without an infinite loop, the comparison value is different, such as 0.1. Otherwise, float and double can be compared, the result value is equal, for example, 0.5.

In this case, we need to apply the knowledge of converting decimals to binary. The so-called multiplication 2 is an integer.

For example, 0.1 is converted to binary:

0.1*2 = 0.2 ---- the integer is 0, so this bit is 0.

0.2*2 = 0.4 ----- the integer is 0. Continue with 0.

0.4*2 = 0.8 ----- the integer is zero and the value is zero.

0.8*2 = 1.6 ----- the integer is 1, and the value is 1.

0.6*2 = 1.2 ---- 1

0.2*2 = 0.4 --- take zero, and the previous loop.

So 0.1 (base 10) = 0.00011 0011 0011... (0011 is an infinite loop digital value)

If such a number has different precision, it will definitely lead to different values.

So :( float) 0.1! = Double (0, 0.1)

But 0.5 (base 10) = 0.1 (base 2), no infinite cyclic digits

So :( float) 0.5 = double (0.5)


Reference: http://www.geeksforgeeks.org/comparison-float-value-c/


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.