為什么if循環不起作用呢?
/* 定義一個int型的一維數組,包含40個元素,用來存儲 每個學員的成績,循環產生40個0~100之間的隨機整數, 將它們存儲到一維數組中,然后統計成績低于平均分的學 員的人數,并輸出出來 */ import?java.util.Random; public?class?HomeWork03{ ??????public?static?void?main(String[]?args){ ??????????int[]?score=new?int[40]; ??????????int?sum=0; ??????????int?average=0; ??????????//int?count=0; ??????????//循環遍歷數組,賦值 ??????????for(int?element:score){ ???????????????Random?random=new?Random(); ???????????????element=random.nextInt(100); ???????????????System.out.println(element); ???????????????sum+=element;? ???????????????} ???????????//求平均值 ???????????????average=sum/40; ???????????????System.out.println("平均值為:"+average); ???????????//循環遍歷數組,如果分數低于平均值,人數就加1 ???????????int?count=0; ???????????for(int?i=0;i<score.length;i++){ ??????????? ?????if(score[i]<average){ ??????????? ????? ??count+=1; ??????????? ?????}? ???????????} ????????????System.out.println("分數低于平均分的人數為:"+count); ??????} }
代碼運行結果為count=40,結果明顯是錯誤的,但是找不到原因。
2017-03-14
?//循環遍歷數組,賦值
??????????for(int?element:score){
???????????????Random?random=new?Random();
???????????????element=random.nextInt(100);
???????????????System.out.println(element);
???????????????sum+=element;?
???????????????}
你這里做循環的時候,只是給總成績付了值,但是成績數組卻沒有賦值,當循環結束的時候數組是空的
2017-03-14
上面循環給數組里的元素賦值有問題,不信你在外面打印一個Arrays.toString(score)看看,元素其實都是0,換成for循環 score[i]這種來賦值就OK