我遇到了一个问题,需要使用方法重载计算球体、圆柱体和锥体的体积。以下是我的代码,绝对没有问题:
import java.util.*;
class Vol_Sph_Cyl_Con
{
void calc_volume(double sp_rd)
{
double volume=(4*3.14*(Math.pow(sp_rd,3)))/3;
System.out.println("Volume of the sphere is "+volume+" cc");
}
void calc_volume(double cyl_rd, double cyl_he)
{
double volume=3.14*(Math.pow(cyl_rd,2))*cyl_he;
System.out.println("Volume of the cylinder is "+volume+" cc");
}
void calc_volume(double con_rd,double con_he,double pie)
{
double volume=(pie*(Math.pow(con_rd,2))*con_he)/2;
System.out.println("Volume of the cone is "+volume+" cc");
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Vol_Sph_Cyl_Con ob=new Vol_Sph_Cyl_Con();
double sp_rad=0.0;
do
{
System.out.println("Enter radius of sphere to calculate the volume (in centimetres)");
sp_rad=sc.nextDouble();
if (sp_rad<=0)
{
System.out.println("Error!");
}
}while (sp_rad<=0);
ob.calc_volume(sp_rad);
double cyl_rad=0.0, cyl_hei=0.0;
do
{
System.out.println("Enter the radius and the height of cylinder respectively to calculate volume (in centimetres)");
cyl_rad=sc.nextDouble();
cyl_hei=sc.nextDouble();
if (cyl_rad<=0 || cyl_hei<=0)
{
System.out.println("Error!");
}
}while (cyl_rad<=0 || cyl_hei<=0);
ob.calc_volume(cyl_rad,cyl_hei);
double con_rad=0.0, con_hei=0.0, pi=3.14;
do
{
System.out.println("Enter radius and height of cone respectively to calculate volume (in centimetres)");
con_rad=sc.nextDouble();
con_hei=sc.nextDouble();
if (con_rad<=0 || con_hei<=0)
{
System.out.println("Error!");
}
}while (con_rad<=0 || con_hei<=0);
ob.calc_volume(con_rad,con_hei,pi);
}
}
这个程序本身没有问题,但是由于这是一个学校项目,我不能在计算圆锥体积的方法中传递参数'pie',因为我们不允许显式地传递不必要的参数。但如果我不这样做,参数数量就会相同。有没有解决办法,或者这只是问题出在问题描述上?
Math.PI
而不是 3.14。 - Bathsheba