編寫一個名爲calculateAverageWeight的靜態方法,將其添加到Bowl類中,該類將傳遞一個Bowl對象數組,並返回數組中Bowls的平均權重。創建一個計算數組平均值的方法(java)
這是碗類:
public class Bowl {
private double weight;
private boolean empty;
private String origin; // country of manufacture
public Bowl(double w, boolean e, String origin) {
weight = w;
empty = e;
this.origin = origin;
}
public double getWeight() {
return weight;
}
public boolean getEmpty() {
return empty;
}
public String getOrigin() {
return origin;
}
public void setEmpty(boolean emptyStatus) {
empty = emptyStatus;
}
public String toString() {
return ("from " + origin + " weight: " + weight);
}
下面的代碼工作:
public static double calculateAverageWeight(Bowl[] bowls)
{
double sum=0;
double average=0;
for(int j=0; j<bowls.length; j++)
{
sum+=bowls[j].getWeight();
average=sum/bowls.length;
}
return average;
}
,但我不明白爲什麼我最近的代碼並沒有因爲他們似乎幾乎完全相同運行我?:
public static double calculateAverageWeight(Bowl[] bowls){
double sum=0;
double k=bowls.length;
for(int j=0; j<bowls.length; j++){
sum=sum+bowls[j].getWeight();}
double average=sum/k;
return average;}
當你運行它會發生什麼? – 2013-03-26 02:15:42
有什麼問題?我們不是介意讀者;你必須實際告訴我們。 – 2013-03-26 02:15:51
您可能想要將該分組中的某個整數轉換爲(double),否則我認爲您會得到一個分配給平均值的整數。我從內存中調試這個,雖然所以我可能是錯的 – 2013-03-26 02:16:54