代码之家  ›  专栏  ›  技术社区  ›  Blank Reaver

球体体积法不起作用

  •  0
  • Blank Reaver  · 技术社区  · 8 年前

    我尝试了许多不同的计算,试图让我的球体体积方法工作。

    我的Sphere类从Circle扩展而来,从Circle中获取面积,并实现了Shape3D接口,该接口允许我使用体积方法。

    然而,我已经在我的方法中尝试了所有这些不同的公式,但没有任何东西能给出球体的精确体积。它总是彻底关闭。

        //return (4/3) * super.area() * radius;
        //return (Double)((4*22*getRadius()*getRadius()*getRadius() )/(3*7));
        //return (4*22*radius * radius * radius )/(3*7);
        //return ( (4/3) * (Math.pow(getRadius(), 3) ) / (Math.PI) );
        //return (getRadius() * getRadius() * getRadius() ) * (Math.PI) * (4/3);
        //return ( super.area() * getRadius() ) * (4/3);
    

    也许我忽略了一些显而易见的事情。当我设置半径并得到它时,半径返回正常值。所以我不知道为什么所有这些如果完全关闭。

    public class Main {
            public static void main(String[] args) {
    
                System.out.println(volume());
            }
    
    
    
            public static double volume() {
            double vol;
            double x = 4/3;
            double y = Math.pow(30.0, 3);
            double z = Math.PI;
            vol = y * z * x;
            return vol;
            //return (4/3) * super.area() * radius;
            //return (Double)((4*22*getRadius()*getRadius()*getRadius() )/(3*7));
            //return (4*22*radius * radius * radius )/(3*7);
            //return ( (4/3) * (Math.pow(getRadius(), 3) ) / (Math.PI) );
            //return (getRadius() * getRadius() * getRadius() ) * (Math.PI) * (4/3);
            //return ( super.area() * getRadius() ) * (4/3);
        }// end sphere volume
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Sash Sinha    8 年前

    这是一个简单的java测试程序,用于计算球体的体积,您可以将其用作判断您做错了什么的参考 4/3 返回一个 int 1. double 代表 ![1.3 recurring 因此会打乱你的计算:

    import java.util.Scanner;
    
    class Main {
      public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
    
        // notice the descriptive variable names rather than x, y and z
        double radius;
        double diameter;
        double volume;
    
        System.out.print("Enter the radius of the sphere:");
        radius = scanner.nextDouble();
        diameter = (radius * 2.0);
        volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3); // instead of 4/3 in yours
        System.out.println("The volume is: " + String.format("%.1f", volume));
      }
    }
    

    Enter the radius of the sphere: 5
    The volume is: 523.6
    

    Google's sphere volume calculator 并确认其给出相同的值:

    enter image description here

        2
  •  1
  •   assembler    8 年前

    而不是

    double x = 4/3;
    

    double x = 4.0/3.0;
    

    double x = 4.0/3;
    

    double x = 4/3.0;