-5

in C language

float a=0.1;

if(a==.1)
  printf("hello");
else
 printf("123");

Output is 123

But for Java

float a=0.1F;

if(a==.1)
  System.out.println("hello");
else
  System.out.println("123");

Ans is hello.

Why?

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33

2 Answers2

2

Here comparison by == first converts float to double and than compares both value.

float real = 0.1f;
double real2 = real;
System.out.println(real2);

OUTPUT

0.10000000149011612

Now you can see when you convert float to double for value 0.1 you will not get the exact value here. Here system will convert your float value to double with extra precision in data.

Same thing happens here when you write if(a==.1) your a will be converted to something like 0.10000000149011612 and than compares with 0.1 which is already double and has exact value 0.1 and so it result to false and must print 123 and not hello that I am sure about.

akash
  • 22,664
  • 11
  • 59
  • 87
0

You're comparing apples and oranges. In the Java case, you should be using

if (a == 0.1F)
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Don't both code snippets use a double literal in the `if`? – user2357112 May 24 '15 at 06:23
  • I think the problem here is that he expects the same (`123`) but is getting `hello` – Anindya Dutta May 24 '15 at 06:29
  • @user2357112 Of course, but the point is that the literals mean different things in the two languages, as already exhibited by the declarations. – user207421 May 24 '15 at 06:34
  • @AnindyaDutta Of course it is. Your point? – user207421 May 24 '15 at 06:34
  • 1
    @EJP: No, the literals mean the same thing (or at least, they mean the same thing on platforms where a C double is IEEE 754 binary64). There's a discrepancy earlier in the code, where one version assigns `float a=0.1;` and one assigns `float a=0.1F;`, but there's no apples-and-oranges problem in the `if` itself. – user2357112 May 24 '15 at 06:36
  • My point is that he's getting the wrong output for a correct program. If he is using `if (a == 0.1)` then it should return `false` since `0.1` is `double`, but it is returning `true` in his case. – Anindya Dutta May 24 '15 at 06:37
  • Actually, I think we might be reading the question differently. I see it as an issue of the float/double comparison working differently in differently languages. You might be interpreting it a different way. – user2357112 May 24 '15 at 06:39