package com.software;public class bianChen6_6 { public static void main(String[] args) {? ? ? int scores[] = new int[]{61,23,4,74,13,148,20};? ? ? int max=scores[0];? ? ? int min=scores[0]; ? ??? ? ? int i = 0;? ? ? double count=0;? ? ? double avg=0;? ? ? for(;i<scores.length;i++){? ? // 如果當前值大于max,則替換max的值? ? ?if(scores[i]>max){? ? ?max = scores[i];? ? ?}? ? // 如果當前值小于min,則替換min的值? ? ?if(scores[i]<min){? ? ?min = scores[i];? ? ?}? ? ?//累加求和? ? ?count = count+scores[i];? ? ? }? ? ? ? ? //求平均值 ?avg = count%scores[i];? ? ? System.out.println("數組中的最大值是"+max);? ? ? System.out.println("數組中的最小值是"+min);? ? ? System.out.println("數組的和值是"+count);? ? ? System.out.println("數組的平均值是"+avg); }}這是我的代碼,運行后怎么提示超出數組長度?幫我看一哈。
6 回答
已采納

IT界小嫩草一枚
TA貢獻4條經驗 獲得超6個贊
為什么會報數組越界。 因為當循環跳出的那一刻是i=scores.length, 即i=7, 在你求平均值的時候寫scores[i]就是scores[7], 你定義的數組下標最大是6, 所以越界
求平均值。 應該是綜合除以個數,即count÷i或者count÷scores.lengh(用這種方式比較好)。
count÷scores.length應該寫成count/scores.length, %是取余。
正確的輸出結果是:?
數組中的最大值是148
數組中的最小值是4
數組的和值是343.0
數組的平均值是49.0
希望能幫到你:)
添加回答
舉報
0/150
提交
取消