how to use math.pi in java

不打扰是莪最后的温柔 提交于 2020-04-07 14:47:30

问题


I am having problems converting this formula V = 4/3 π r^3. I used Math.PI and Math.pow, but I get this error:

';' expected

Also, the diameter variable doesn't work. Is there an error there?

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:


You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

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



回答2:


Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into 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);
    }

}



回答3:


Replace

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

With:

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



回答4:


Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it

Ex:

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


来源:https://stackoverflow.com/questions/12594058/how-to-use-math-pi-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!