-2
double multiply() 
{
 double x=(2/3)*3.14*1.02;
 System.out.print(x);

 double y=0.666*3.14*1.02; /*(2/3)=0.666...*/
 System.out.print(y);
}

Output: x=0.0 y=SomeNumber

please explain this?

  • 4
    Aren't you familiar with the joke? You have 6 programmers and 5 slices of cake. How much cake does each programmer get? 0, of course. – Neil Feb 19 '16 at 14:13

5 Answers5

2
(2/3) is 0.

because both are integers. To solve this, use a cast or make it clear that your number is not an integer:

double x=(2/3d)*3.14*1.02;

Now you have an integer divided by a double, which results in a double.

Some more to read about this: http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html

Tilman Hausherr
  • 17,731
  • 7
  • 58
  • 97
1

(2/3) is computed first (because of the parentheses), and in integer arithmetic (since the number literals are of type int). The fractional part is discarded.

It is therefore an int type with a value of 0. The entire expression is therefore zero.

The obvious remedy is to remove the parentheses and write 2.0 / 3.0 instead. Some folk prefer an explicit cast, but I find that ugly.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

2/3 = 0 because they don't have explicit cast to double they are integers. The whole expression becomes: double x=0*3.14*1.02; which is 0.

Alexandru Cimpanu
  • 1,029
  • 2
  • 14
  • 38
0

because data type of both 2 and 3 is int and int/int gives you int which in your case 2/3 is 0. Try using 2.0/3 or 2/3.0 you will get the required answer.

0

Suffix every number with a 'd' to be sure you are dealing with doubles

Benjamin
  • 3,350
  • 4
  • 24
  • 49