配列を使用して入力した数字から最大値・最小値・平均値を求めるプログラム
入力が一定ではないならリストの方が良いんだけどなぁ…
っていうのは学生の課題だから仕方ない?
とりあえず、配列の要素数は5にしています。
いつも通り、機能要件を満たす最低限のコードしか書いてません。
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); int[] array = new int[5]; int min = Integer.MAX_VALUE; int max = 0; int sum = 0; for(int element: array){ element = s.nextInt(); min = Math.min(min,element); max = Math.max(max,element); sum += element; } System.out.printf("Min=%d\n",min); System.out.printf("Max=%d\n",max); System.out.printf("Ave=%f\n",(float)sum/array.length); } }
入力
3 6 7 9 12
出力
Min=3 Max=12 Ave=7.400000