Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Comparing float with a value

    • 1
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 209
    Answer it

    Hi everyone,
    I was looking at two C programs given here below, attached in the question.txt file.
    I can't write my code here because in the preview section my code looks very ambiguous.
    These codes are giving different outputs but i was thinking of getting the same output, can you please explain why they are giving such outputs.

 1 Answer(s)

  • The output of first program is ELSE IF which means the expression x == 0.1 returns false and expression x == 0.1f returns true.

    Let consider the of following program to understand the reason behind the above output.

    #include
    int main()
    {
       float x = 0.1;
       printf("%d %d %d", sizeof(x), sizeof(0.1), sizeof(0.1f));
       return 0;
    }

    The output of above program is 4 8 4 on a typical C compiler. It actually prints size of float, size of double and size of float.

    The values used in an expression are considered as double (double precision floating point format) unless a f is specified at the end. So the expression x==0.1 has a double on right side and float which are stored in a single precision floating point format on left side. In such situations float is promoted to double. The double precision format uses uses more bits for precision than single precision format. Note that the promotion of float to double can only cause mismatch when a value (like 0.1) uses more precision bits than the bits of single precision. Also you can refer to http://www.geeksforgeeks.org/floating-point-representation-basics/ for representation of floating point numbers.

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: