come usare la matematica.pi in java


Sto avendo problemi a convertire questa formula V = 4/3 π r3. Ho usato Math.Pi e Math.pow, ma è qui che inizia il problema. Ottengo questo errore (ogni volta),

"; " atteso

Inoltre, la variabile diameter non funziona. C'è un errore lì?

import java.util.Scanner;

import javax.swing.JOptionPane;

public class NumericTypes    
{
    public static void main (String [] args)
    {
        double radius;
        double volume;
        double diameter;

        diameter = JOptionPane.showInputDialog("enter the diameter of a sphere.");

        radius = diameter / 2;

        volume = (4 / 3) Math.PI * Math.pow(radius, 3);

        JOptionPane.showMessageDialog("The radius for the sphere is "+ radius
+ "and the volume of the sphere is ");
    }
}
Author: Sam, 2012-09-26

4 answers

Manca l'operatore di moltiplicazione. Inoltre, vuoi fare 4/3 in virgola mobile, non la matematica intera.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^
 42
Author: David Yaw, 2012-09-26 03:13:44

La tua variabile diameter non funzionerà perché stai cercando di memorizzare una stringa in una variabile che accetterà solo un doppio. Affinché funzioni è necessario analizzarlo

Es: diametro = Doppio.parseDouble(JOptionPane.showInputDialog ("inserire il diametro di una sfera.");

 1
Author: Mark, 2013-10-24 06:49:10

Ecco l'uso di Math.PI per trovare la circonferenza del cerchio e dell'area Per prima cosa prendiamo Radius come stringa nella finestra di messaggio e lo convertiamo in integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}
 1
Author: tabish ali, 2016-02-19 07:43:57

Sostituire

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

Con:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
 -1
Author: user3394530, 2017-10-20 21:55:14