dポイントプレゼントキャンペーン実施中!

問題7-1:次の配列データの合計と平均を求めるプログラムを作成してください。

double [] x = { 12.3, 45.4, 45.9, 3.56, 6.6, 8.9, 2.3, 0.5, 4.3, 1.2, };

(自分が書いたもの)
public class Sample8_4 {
public static void main(String[] args) {

double[] x = { 12.3, 45.4, 45.9, 3.56, 6.6, 8.9, 2.3, 0.5, 4.3, 1.2, };
double sum = 0.0;

for (int i = 0; i < x.length; i++) {
;
sum += x[i];

double average = sum / x.length;

System.out.println("平均:" + average + ",合計:" + sum);

}

}
}

(実行結果)

平均:1.23,合計:12.3
平均:5.7700000000000005,合計:57.7
平均:10.36,合計:103.6
平均:10.716,合計:107.16
平均:11.376,合計:113.75999999999999
平均:12.266,合計:122.66
平均:12.495999999999999,合計:124.96
平均:12.546,合計:125.46
平均:12.975999999999999,合計:129.76
平均:13.095999999999998,合計:130.95999999999998

(答え)
総計:130.95999999999998, 平均:13.095999999999998


for文についていまいち理解できていません(拡張for文も)
回答よろしくお願いします。

A 回答 (2件)

public class Sample8_4 {


public static void main(String[] args) {

double[] x = { 12.3, 45.4, 45.9, 3.56, 6.6, 8.9, 2.3, 0.5, 4.3, 1.2, };
double sum = 0.0;

for (int i = 0; i < x.length; i++) {

sum += x[i];

}

double average = sum / x.length;   //ここ2行を外に出すだけ。
System.out.println("平均:" + average + ",合計:" + sum);

}
}
    • good
    • 0
この回答へのお礼

すいません凡ミスでした・・
回答ありがとうございます。

お礼日時:2013/12/24 16:01

今JAVAの実行環境がないので実行していませんがこんな感じでできると思います。



double型は計算すると誤差が発生します。
ですのでBigDecimalクラスを使って計算します。
(そこまで正確に計算する必要なければdouble型でもOKです)

public class Sample8_4 {
public static void main(String[] args) {

double[] x = { 12.3, 45.4, 45.9, 3.56, 6.6, 8.9, 2.3, 0.5, 4.3, 1.2, };

BigDecimal sum = new BigDecimal();

for (double y : x) { //拡張for文

sum = sum.add(new BigDecimal(y));

}

BigDecimal average = sum.divide(x.length, 5, BigDecimal.ROUND_HALF_UP);//小数点以下第5位まで求める

System.out.println("平均:" + average.toString() + ",合計:" + sum.toString());

}
}
    • good
    • 0
この回答へのお礼

BigDecimalクラスですか。
知らない言葉だったのでちょっと調べてみます。

ありがとうございました。

お礼日時:2013/12/24 16:03

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!