-2

I created a simple program to calculate the volume of a sphere. But something wrong with the following code line

double volume=(4/3)*PI*radius*radius*radius;

producing the wrong answer.but if i change that to

double volume=PI*radius*radius*radius*4/3;

now it's giving the correct answer.

But both equations are perfectly alright according algebra. So why I get the wrong answer for the first equation?

catch23
  • 17,519
  • 42
  • 144
  • 217
user3112250
  • 53
  • 1
  • 10
  • 1
    A programming language is not math. There are many differences ("traps"). I recommend you read a book on the programming language (so Java in this case). – Bernd Elkemann Feb 15 '14 at 14:54
  • you should use casting for integer division, or change one operator to double - `4.0 / 3` – catch23 Feb 15 '14 at 14:55

3 Answers3

3

4/3 is interpreted as integer-division which means flooring - you have to explicitely state a floating-point division: (double) 4/3 or 4.0/3.

Smutje
  • 17,733
  • 4
  • 24
  • 41
2

4/3 == 1. Integer division.

Try 4.0/3 for float, or divide by 3 at the end.

djechlin
  • 59,258
  • 35
  • 162
  • 290
0

It is because (4/3) is integer division and equals 1 by truncation. You should write:

double volume = (double) 4/3 *PI*radius*radius*radius;

or

double volume = 4.0/3 *PI*radius*radius*radius;
4pie0
  • 29,204
  • 9
  • 82
  • 118