实现代码:
int Largest(int list[], int length) { int i,max; for(i = 0; i < (length – 1); i ++ ) { if(list[i] > max) { max=list[i]; } } return max; }
测试代码:
import java.util.Scanner; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sca = new Scanner(System.in); System.out.println("输入六个数:"); int num[] = new int[6]; for(int i=0;i<6;i++) { num[i] = sca.nextInt(); } Largest(num,6); } static void Largest(int list[],int length) { int i,max; if(list == null) { System.out.println("无最大值!"); } else { max = list[0]; for(i=0; i<(length); i++) { if(list[i]>max) { max = list[i]; } } System.out.println("最大值为:"+max); } } }
结果截图:
错误分析:
1.max没有赋初值。需要在max非空的时候赋给max一个数组0~5中的一个数。(不能赋0值,因为有可能输入的都是负数)。
2.length在for循环中多减了1,导致只能在输入的前五个数中进行比较最大值。
3.没有考虑当输入的数为空时的情况,所以加入一个if判断是否list为空,如果为空,则输出没有最大值。