-5

When the values are equal by using the equality operator , output shows Failure instead of success. Is this the problem with versions of compilers? Screen shot of the program attachedProgram coded in System and Output

void main()
        {
            float k = 0.1;
            if (k == 0.1)
                printf("Success");
            else
                printf("Failure");
        }
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Krishna Krish
  • 79
  • 1
  • 8
  • 1
    Before asking **please** consult the C info page! And don't post images of text! – too honest for this site Feb 27 '17 at 17:58
  • You should always assume it's impossible to compare floating-point numbers for equality. – byxor Feb 27 '17 at 19:21
  • The reason that comparing to 0.1 does not work is that 0.1 is a double and is not the same number as k, since k is a float and has fewer significant digits in its representation. And you can compare floating point numbers for equality, but only if the two values were assigned in exactly the same way. But that is usually rare, so it is best to compare the absolute value of their difference to a small positive value to decide if they are "close enough" to be considered equal. – FredK Feb 27 '17 at 19:35

1 Answers1

0

Look at this:

Predict the output of following C program.

#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");
}
The output of above program is “ELSE IF” which means the expression “x == 0.1” returns false and expression “x == 0.1f” returns true.

Taken from here

clockw0rk
  • 576
  • 5
  • 26