我正试图解决这个问题:
编写一个名为areFactors的方法,它接受一个整数n 和一个整数数组,如果数组中的数字返回true 是n的所有因素(也就是说n可以被所有这些因子整除)。
这是我的答案之一:
public static boolean arefactors(int n, int[] factors){
for (int factor:factors){
if (n % factor != 0)
return false;
}
return true;
}
但是为什么当我反向并首先返回'true'时,程序无法正常运行并且无论我在数组中使用什么整数,它总是返回true?在这种情况下:
public static boolean areFactors( int n, int[] factors) {
for (int factor: factors) {
if ( n % factor==0)
return true;
}
return false;
}
答案 0 :(得分:1)
在第一种方法中,如果true
数组中的所有数字都是factors
的因子,则返回n
(即返回false
如果任何数字不是一个因素,这意味着只有在您检查完所有数字后才返回true
。
在第二种方法中,如果 true
数组中的任何数字是factors
的因子,则返回n
(因为您返回{{1}第一次找到因子true
)。
因此,这两种方法产生不同的输出。
答案 1 :(得分:1)
因为您必须返回true
,因为int
数组的所有factors
都可以被n
整除。
但是您在第二个代码中的第一个匹配处返回true
:
public static boolean areFactors( int n, int[] factors) {
for (int factor: factors) {
if ( n % factor==0)
return true; // only first element(s) of factors may be divisible
// by n and not the next one. But too late you returned true
}
return false;
}
虽然您的第一个代码是正确的:
public static boolean arefactors(int n, int[] factors){
for (int factor:factors){
if (n % factor != 0)
return false; // if any is not divisible by n, you return false
}
return true; // if you go there, it means all numbers are divisible by n
// you can then return true
}