38

我在转换这个公式时遇到问题V = 4/3 π r^3。我使用Math.PIand Math.pow,但我收到此错误:

';' 预期的

此外,直径变量不起作用。那里有错误吗?

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 ");
    }
}
4

4 回答 4

55

您缺少乘法运算符。另外,你想4/3用浮点数做,而不是整数数学。

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^
于 2012-09-26T03:13:44.673 回答
4

代替

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

和:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
于 2017-10-20T19:17:25.223 回答
4

这是Math.PI查找圆的周长和面积的用法首先我们将半径作为消息框中的字符串并将其转换为整数

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);
    }

}
于 2016-02-19T07:36:26.417 回答
1

您的直径变量将不起作用,因为您试图将字符串存储到仅接受双精度的变量中。为了让它工作,你需要解析它

前任:

diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
于 2013-10-24T06:49:10.983 回答