-1

For float value the output is coming"okNOT OK", It should have shown "okOK". But with other datatypes it is working fine. Why is it hapenning?

#include<stdio.h>
int main()
{
    float a=0.5, b=0.7;
    if(a==0.5)
    printf("ok");
    else
    printf("not ok");
    if(b==0.7)
    printf("OK");
    else
    printf("NOT OK");
    return 0;
}

1 Answers1

2

By default, decimal values are double, which means you compare 0.7f (float) with 0.7 (double). These values are different, as double uses more bits to save data about the number itself. To fix your problem, change your if statements to:

if(a == 0.5f)
    ...
if(b == 0.7f)
    ...

This way you will compare float a, b with corresponding float values.

whiskeyo
  • 873
  • 1
  • 9
  • 19