2

当我的所有其他方法都正常工作时,我似乎无法弄清楚为什么我的 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 方法,但我目前对解决手头问题的方法知之甚少。

4

1 回答 1

4

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

于 2013-02-22T16:44:53.570 回答