如何从6个数字循环中取出前3个随机数



所以我应该在Java中制作一个重载程序。我已经制定了两种方法来平均6个数字和前3个数字。但我不知道如何将其存储到这两种方法的参数中。到目前为止,这是我的代码:

Random number = new Random();
Scanner input = new Scanner(System.in);
int num;
int sum = 0;
for(int counter = 1; counter <=6; counter++){
num = 1 + number.nextInt(20);
System.out.printf("Random number #%s: %s%n",counter,num);
}
}
public static int avg (int a, int b, int c, int d, int e, int f){
return ((a+b+c+d+e+f)/6);
}
public static int avg (int a, int b, int c){
return((a+b+c)/3);
}

创建一个数组或int列表,并将随机数存储到数组/列表中。然后,您可以用数组/列表的元素调用这两个方法

int[] array = new int[6];
for(int counter = 1; counter <=6; counter++){
num = 1 + number.nextInt(20);
array[counter-1] = num;
System.out.printf("Random number #%s: %s%n",counter,num);
}
}
int avg1 = avg(array[0],array[1],array[2]);
int avg2 = avg(array[0],array[1],array[2],array[3],array[4],array[5]);

在不使用数组的情况下,创建6 int并删除for循环

int i1 = 1 + number.nextInt(20);
int i2 = 1 + number.nextInt(20);
int i3 = 1 + number.nextInt(20);
int i4 = 1 + number.nextInt(20);
int i5 = 1 + number.nextInt(20);
int i6 = 1 + number.nextInt(20);

然后将函数的返回类型更改为双重

public static double avg (int a, int b, int c, int d, int e, int f){
return ((a+b+c+d+e+f)/6.0); //change 6 to 6.0 so it doesn't do integer divide
}
public static double avg (int a, int b, int c){
return((a+b+c)/3.0); //change 3 to 3.0 for same reason as above
}
double avg1 = avg(i1,i2,i3);
double avg2 = avg(i1,i2,i3,i4,i5,i6);

我认为您不允许使用数组,所以只需将每个数组分配给一个变量。

num1 = 1 + number.nextInt(20);
num2 = 1 + number.nextInt(20);
num3 = 1 + number.nextInt(20);
// and so on for six numbers.

然后

int avgerage = avg(num1, num2, num3, ...);

请注意,由于您没有使用双倍,因此您的平均值不会有小数。

否则,将数字放在一个数组中。

你也可以这样做:

public int avg(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum/array.length;
}

如果允许,我建议将您的值从int更改为double

最新更新