带有数学运算符和数组的 Java Return 方法



>我需要创建一个返回 x/2 除数的函数,将它们放入数组中并返回此数组。"x"是来自不同方法的用户输入。

public static int[] findDividers(int[] x) {

int[] array = new int[x/2];
for(int i=1; i <= array.length; i++) {
// int c = x/i;
if (x%i == 0) {
array[i] = i;   
System.out.println(i);
}
return array;
}

我不断收到错误:

"运算符/和 % 未为参数类型定义 int[], int">

有什么建议吗?

如果你只是将参数修改为 findDividers 方法,你的函数应该没问题。它应该如下:

//Will return dividers of x, not x/2
public static int[] findDividers(int x) { //not int[] x
//if x is of type int[] i.e an array, it makes no sense to
//use the '/' and '%' operators on it. That's why the compiler was
//complaining on your code
int[] array = new int[x/2];
for(int i=1; i <= array.length; i++) {
// int c = x/i;
if (x%i == 0) {
array[i-1] = i;   
System.out.println(i);
}
}
return array;
}

这是我的建议,它将返回一个仅包含分隔符的数组,因此findDividers(10)将返回数组 [1,2,5]

public static int[] findDividers(int x) {
int roof = x / 2;
int[] values = new int[roof];
int test = 1;
int count = 0;
while (test <= roof) {
if (x % test == 0) {
values[count] = test;
count++;
}
test++;           
}
return Arrays.copyOf(values, count);
}

最新更新