Java 2 different formula problems

I want to calculate the scope of a sphere using a Java program. So I used

double result = 4/3*Math.PI*Math.pow(r,3); 

This formula gives the wrong answers.

Like Java opt 4/3 program, but if I change it to

 double result= Math.PI*Math.pow(r,3)*4/3; 

he gives me the correct answer. Does anyone know what is going on?

+5
source share
3 answers

The difference in results is related to the priority of the operator. In Java, multiplication and division have the same priority and therefore are evaluated from left to right.

So your first example is equivalent

 double result = (4/3)*Math.PI*Math.pow(r,3); 

Here 4/3 is a division of two integers, and in Java in such cases an integer division is performed with the result 1. To solve this problem, you must explicitly make sure that one or both of the operands are double:

 double result = (4.0/3.0)*Math.PI*Math.pow(r,3); 

The second example, however, is equivalent

 double result = (Math.PI*Math.pow(r,3)*4)/3; 

Here the part of Math.PI*Math.pow(r,3)*4 is evaluated as double, and therefore we no longer have integer division, and you get the correct result.

+3
source

This is due to the order in which casting occurs in Java (or C, for that matter).

For details on operator precedence, see http://introcs.cs.princeton.edu/java/11precedence/ .

In your first case, since the multiplication and division operators are calculated from left to right, the first java operation interprets 4/3. Since both operands are integers, java computes the integer division, the result of which is 1.

In your second case, the first operation is double multiplication: (Math.PIMath.pow (r, 3)). The second operation multiplies the double (Math.PIMath.pow (r, 3)) by an integer (4). This is done by casting 4 into double and double multiplication. Finally, java must split the double (Math.PI * Math.pow (r, 3) * 4) by an integer (3), which java performs as double division after casting 3 into double. This gives you the result you expect.

If you want to correct your first answer, first drop 3 first:

  4/ (double)3 

and you get the expected result.

+5
source

4/3 is the division between two int , so Java assumes the result is also int (in this case, it results in a value of 1 ). Change it to 4.0/3.0 and everything will be fine, because 4.0 and 3.0 interpreted as double Java.

 double result = 4.0 / 3.0 * Math.PI * Math.pow(r,3); 
+2
source

Source: https://habr.com/ru/post/1208819/


All Articles