2017-10-04 34 views
0

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

我的Sphere类是从Circle扩展的,以便从圆圈中获取区域,并实现了我的Shape3D接口,该接口允许使用我的体积方法。

但是,我已经尝试了所有这些不同的公式用于我的方法,并且没有任何东西可以给我一个精确的球体体积。它总是彻底关闭。 (4 * 22 *半径*半径*半径)/(3 * 7);(3 * 6 *)*但它仍然关闭。

//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); 

我将为我的Shape抽象类,我的Circle类和我的Sphere类以及我的Shape3D接口附加我的代码。

也许我忽略了一些明显的东西。当我设置半径并得到它时,半径恢复正常。所以我不确定为什么每一个这些如果完全关闭。

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 
} 
+1

'4/Java中3'是不是你认为它是。 – jsheeran

+1

这个问题目前包含了很多“额外”的代码,这对实际问题来说似乎是多余的。它使浏览更难以找到问题。你能想出一个可以说明失败的_minimal_例子吗?如果这是一个算术错误,应该可以通过几行'main'函数重现它。 (甚至可能是因为这个最小的例子,你会发现这个bug!) – yshavit

+1

@jsheeran很好的接收!这是“为什么是1/3 == 0的结果?”(https://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0)“ (尽管我现在不能投票结束)。 – yshavit

回答

1

下面是计算球体,你可以作为参考使用你在做什么错这是4/3返回int的音量一个简单的java测试程序,而非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

+1

谢谢你,这很完美。 我相信我的错误是在4/3中做出的,应该是4.0/3.0 非常感谢。 –

+0

能否请你解释为什么我说4而不是4.0做出了如此巨大的差异? –

+0

@BlankReaver添加了更明确的解释。 – shash678

1

而不是

double x = 4/3; 

尝试

double x = 4.0/3.0; 

double x = 4.0/3; 

double x = 4/3.0;