-2

I have this code:

    float number1 = 2f / 12;
    System.out.println(number1);
    int number2 = 6;
    float x = number1 * number2;
    System.out.println(x);

And as output I get:

0.16666667
1.0

Why? When I multiply number1 and number2, number2 should be promoted to float type, and I should get a 0.96

When I modify my code to:

    float number1 = 0.16f;
    System.out.println(number1);
    int number2 = 6;
    float x = number1 * number2;
    System.out.println(x);

I get good result:

0.16
0.96

Why operation float = float * int in first example produces the bad result?

The Nightmare
  • 701
  • 5
  • 16
  • 36

2 Answers2

2

Because in second case you defined:

float number1 = 0.16f;
//0.16*6=0.96;

But for the first case you have:

2 / 12 = 0.166666667    
0.166666667*6=1
Maksym
  • 4,434
  • 4
  • 27
  • 46
0

number2 should be promoted to float type

Number 2 got promoted to float.

and I should get a 0.96

You should get 1.0, because:

2 / 12 * 6 = 2 / 2 = 1

0.16 * 6 = 0.96

... and that's why. It has nothing to do with computational int vs float arithmetic in this case, it's just arithmetic. Do the math first!

  • dear downvoter, would you care to elaborate on the deficiencies of this answer? –  Dec 16 '14 at 16:35