Problem when calculating time

Asked

Viewed 117 times

0

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

So far so good, at the time of rotating, wheel quiet, the problem is that it does not return a volume value, in how much 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);

    }
}

2 answers

3


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

Change to:

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

The letter d, after the figures, indicates that the result of the transactions must be regarded as a double, to maintain the decimal places.

0

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

The whole code would look 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);

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.