2017-10-04 35 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;