锥体积法返回零

时间:2013-02-22 16:43:22

标签: java methods

当我的所有其他方法都正常工作时,我似乎无法弄清楚为什么我的coneVolume方法返回零。

import java.util.Scanner;

public class P56old{
public static double sphereVolume(double r){
    double sphereVolume = (4/3)*(Math.PI)*(Math.pow(r, 3));
    return sphereVolume;
}
public static double sphereSurface(double r){
    double sphereSurface = 4 * (Math.PI) * Math.pow(r, 2);
    return sphereSurface;
}
public static double cylinderVolume(double r, double h){
    double cylinderVolume = (Math.PI) * (Math.pow(r, 2)) * h;
    return cylinderVolume;
}
public static double cylinderSurface(double r, double h){
    double cylinderSurface = 2 * (Math.PI) * (Math.pow(r, 2)) + 2 * Math.PI * r * h;
    return cylinderSurface;
}
public static double coneVolume(double r, double h){
    double coneVolume = (1/3) * Math.PI * (Math.pow(r,2)) * h;
    return coneVolume;
}
public static double coneSurface(double r, double h){
    double s = Math.sqrt(Math.pow(r,2) + Math.pow(h, 2));
    double coneSurface = Math.PI * Math.pow(r,2) + Math.PI * r * s;
    return coneSurface;
}
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please give the radius: ");
    double r = in.nextDouble();
    System.out.print("Please give the height: ");
    double h = in.nextDouble();

    double coneVolume = coneVolume(r,h);
    double sphereVolume = sphereVolume(r);
    double sphereSurface = sphereSurface(r);
    double cylinderVolume = cylinderVolume(r,h);
    double cylinderSurface = cylinderSurface(r,h);
    double coneSurface = coneSurface(r,h);

    System.out.println("The Sphere Volume is " + sphereVolume);
    System.out.println("The Sphere Surface is " + sphereSurface);
    System.out.println("The Cylinder volume is " + cylinderVolume);
    System.out.println("The Cylinder Surface is " + cylinderSurface);
    System.out.println("The Cone Volume is " + coneVolume);
    System.out.println("The Cone Surface is " + coneSurface);
}
}

我很欣赏有关此事的任何见解,任何批评都表示赞赏。我认为这可能与所有公共类有关,也许另一种方法正在影响coneVolume方法,但我目前还不太了解方法来解决手头的问题。

1 个答案:

答案 0 :(得分:4)

当你做1/3时,它会进行整数除法,结果为0(余数为1)。乘以0得到0.执行1.0 / 3.0,它将正确计算近似值的三分之一。