2015-06-20 21 views
-2

我似乎無法得到這組代碼來返回雙CubicCent上的答案。我知道1立方厘米到釐米釐米的確切答案應該是3785.41178,但它不會返回小數點,而我的克數函數只返回一位小數。提前致謝。常量設置爲雙不會返回雙

public class Volume { 
public static final double Liters_Per_Gallon = 3.785; 
public static final double Cubic_Cent_Per_Liter = 1000.0; 
public static final double Ounces_Per_Pound = 16.0; 
public static final double Grams_Per_Ounce = 28.35; 
private double pounds; 
private double gallons; 
double grams; 
double CubicCent; 

/** 
* @return the gallons 
*/ 
public double getGallons() { 
    return gallons; 
} 

/** 
* @param gallons 
*   the gallons to set 
*/ 
public void setGallons(double gallons) { 
    this.gallons = gallons; 
} 

/** 
* @return the pounds 
*/ 
public double getPounds() { 
    return pounds; 
} 

/** 
* @param pounds 
*   the pounds to set 
*/ 
public void setPounds(double pounds) { 
    this.pounds = pounds; 
} 

public double getCubicCent() { 
    double liters = gallons * Liters_Per_Gallon; 
    CubicCent = liters * Cubic_Cent_Per_Liter; 
    return CubicCent; 
} 
public double getGrams() { 
    double ounces = pounds * Ounces_Per_Pound; 
    grams = ounces * Grams_Per_Ounce; 
    return grams; 
} 
+1

這個問題很可能在於如何打印結果 - 小數位對於double來說沒有意義,因爲它是二進制浮點類型。請剝離課程以重現問題所需的內容,並添加使您認爲自己獲得一位小數的代碼。 –

回答

0

爲了得到您想要的答案,您需要在初始化中更準確地進行Liters_Per_Gallon初始化。例如,使用

public static final double Liters_Per_Gallon = 3.785411784; 

作爲結果給出3785.411784。你將得到雙精度極限,1000倍的恆定值。

+0

太棒了,感謝Patricia完美的修復了它。我現在明白了,它只是以與計算數字相同的精確度回報結果。 – Jetster220