gpt4 book ai didi

java - coneVolume 方法返回零

转载 作者:行者123 更新时间:2023-11-30 07:18:53 25 4
gpt4 key购买 nike

我似乎无法弄清楚为什么我的 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);
}
}

我将不胜感激对此事的任何见解,并感谢任何批评。我认为这可能与所有公共(public)类有关,也许另一种方法正在影响 coneVolume 方法,但我目前对方法的了解还不足以解决手头的问题。

最佳答案

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

关于java - coneVolume 方法返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15029059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com