【发布时间】:2014-07-29 04:22:32
【问题描述】:
问题: 编写一个将可变数量的整数作为输入的方法。该方法应将整数的平均值作为双精度值返回。编写一个完整的程序来测试该方法。
下面的代码创建了一个包含 10 个整数的数组并找到它们的平均值。但是,我需要它来创建可变数量的参数(int...a),其中输入的任意数量的整数可以被平均。谁能帮帮我。谢谢。
我的代码:
package average.pkgint;
import java.util.Scanner;
public class AverageInt {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int [] number = new int [10];
Scanner b = new Scanner(System.in);
System.out.println("Enter your 10 numbers:");
for (int i = 0; i < number.length; i++) {
number[i] = b.nextInt() ;
}
System.out.println("The average is:"+Avnt(number));
}
public static int Avnt(int [] a){//declare arrays of ints
int result = 1;
int sum = 0;
//iterate through array
for (int num : a) {
sum += num;
}
double average = ( sum / a.length);//calculate average of elements in array
result = (int)average;
return result;
}
}
【问题讨论】:
-
不要使用
int作为sum的类型。您只需 2 个整数 (Integer.MAX_VALUE + 1 == Integer.MIN_VALUE) 就可以实现溢出。请改用 long 或 double。
标签: java methods integer arguments variadic-functions