如何在java中使用math.pi

如何在java中使用math.pi,java,pi,Java,Pi,我在转换这个公式时遇到问题V=4/3πr^3。我使用了Math.PI和Math.pow,但我得到了以下错误: “;”期望 此外,直径变量不起作用。有错误吗 import java.util.Scanner; import javax.swing.JOptionPane; public class NumericTypes { public static void main (String [] args) { double radius;

我在转换这个公式时遇到问题
V=4/3πr^3
。我使用了
Math.PI
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/3
,而不是整数运算

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

您的diameter变量无法工作,因为您试图将字符串存储到只接受双精度的变量中。为了让它工作,您需要解析它

例:

diameter=Double.parseDouble(JOptionPane.showInputDialog(“输入球体的直径”);

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

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

}
替换

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


您将遇到的下一个问题在这里得到了回答:也许可以对您在这里所做的事情添加一些解释?@orhtej2(4/3)返回1。因此他用4乘以一个浮点数,得到一个浮点数,然后用3除以,得到一个浮点数结果。
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;