0

When i write for example:

double d = (4/3)*6; 

Why does it sees 4/3 as 1(int?) not 1.333 and the result is 6 not 8?

Thanks.

Steven Magdy
  • 93
  • 1
  • 8

3 Answers3

2

4/3 is equal to 1, since it's dividing two integers using integer division. 4.0/3 will give you the result you expect, since it will use floating point division.

Eran
  • 374,785
  • 51
  • 663
  • 734
0

You are calculating the value in integer arethmetic and asigning the result to a double value, however the result is still a whole number. You can force floating point arithmetic, by making the first operand a double (or if they are input variables multiply with 1.0):

double d = (4.0/3)*6; 

If the values are inputs:

int a = 4;
int b = 3;
int c = 6;

You can force the conversion by multiplying with 1.0:

double d = (a*1.0/b)*c; 
hotzst
  • 6,834
  • 8
  • 36
  • 59
0

Because every number without a specification is handelt as an integer.

If you use 1.0 it will be a double.

For the other formates you could use 1f for float, 1l for long or an other way to represent a double would be 1d.

SomeJavaGuy
  • 7,237
  • 2
  • 19
  • 33