如何在java中使用math.pi

2022-09-01 04:27:05

我在转换此公式时遇到问题。我用了 和 ,但我得到这个错误:V = 4/3 π r^3Math.PIMath.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 ");
    }
}

答案 1

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

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

答案 2

以下是查找圆和面积的周长用法 首先,我们将Radius作为消息框中的字符串并将其转换为整数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);
    }

}

推荐