Problem in calculating

0

I am doing an exercise that receives a value from the radius of the sphere, and then I do operations with formulas already proposed by the exercise.

So far so good, at the time of running, it runs smoothly, the problem is that it does not return a volume value, as long as the others return quietly.

package pct;
import java.util.Scanner;
import java.lang.Math;
public class exer01 {
    public static void main(String[] args) {
        Scanner teclado = new Scanner (System.in);
        double c, a, v, raio = 0;


        System.out.println("Digite o raio da esfera: ");
        raio = teclado.nextDouble();

        c = 2*3.14*raio;
        a = 3.14*Math.pow(raio, 2);
        v = 3 / 4*3.14*Math.pow(raio, 3);

        System.out.println("O valor do comprimento é: "+c);
        System.out.println("O valor da área é: "+a);
        System.out.println("O valor do volume: "+v);

    }
}
    
asked by anonymous 11.03.2017 / 17:45

2 answers

3

The calculation does not give the expected result because it is being done with integer constants, causing the fractional parts to be lost.

Change to:

v = 3d / 4d * 3.14 * Math.pow(raio, 3);

The letter d , following the constants, indicates that the result of the operations should be considered as double , in order to keep the decimal places.

    
11.03.2017 / 18:00
0

You have inverted the formula, 3 is the divisor and not the dividend. The correct formula for the volume of a sphere is (4 * 3.14 * Math.pow(raio, 3)) / 3 . In addition, the Math class has a constant for PI that you can use.

The complete code looks like this:

package pct;
import java.util.Scanner;
import java.lang.Math;
public class exer01 {
    public static void main(String[] args) {
        Scanner teclado = new Scanner (System.in);
        double c, a, v, raio = 0;


        System.out.println("Digite o raio da esfera: ");
        raio = teclado.nextDouble();

        c = 2* Math.PI * raio;
        a = Math.PI * Math.pow(raio, 2);
        v = (4 * Math.PI * Math.pow(raio, 3)) / 3;

        System.out.println("O valor do comprimento é: "+c);
        System.out.println("O valor da área é: "+a);
        System.out.println("O valor do volume: "+v);

    }
}
    
11.03.2017 / 18:05