[英]how to use math.pi in java
我在轉換此公式時遇到問題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);
^^ ^
這里使用Math.PI
來查找圓的周長,區域首先我們將Radius作為字符串在Message Box中並將其轉換為整數
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);
}
}
你的直徑變量不起作用,因為你試圖將一個String存儲到一個只接受double的變量中。 為了使它工作,你需要解析它
例如:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
更換
volume = (4 / 3) Math.PI * Math.pow(radius, 3);
附:
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.