我正在尝试计算20 ad 40之间的数字可以被4整除。
我的值是打印There are 10 numbers divisible by 4
而不是There are 6 numbers divisible by 4
我对编程很新,我不确定这是我的数学是错误的,我的返回值还是我的for循环...为什么我得到10而不是6?
class Divisibility{
public static void main(String[] args) {
int start = 20, stop = 40, divisor = 4;
int count = countDivisible(start, stop, divisor);
System.out.println("There are " + count + " numbers divisible by " + divisor);
}
public static int countDivisible(int start, int stop, int divisor) {
int numbers = start;
for (int i = start; i <= stop; i++)
if ((i % divisor) == 0)
numbers = i / divisor;
return numbers;
}
}
答案 0 :(得分:0)
您将返回除分数的结果。
public static int countDivisible(int start, int stop, int divisor) {
int numbers = 0;
for (int i = start; i <= stop; i++){
if ((i % divisor) == 0){
numbers++;
}
}
return numbers;
}
答案 1 :(得分:0)
您的结果为numbers = i / divisor
,最终为40/4。
我认为这就是你要找的东西:
public static int countDivisible(int start, int stop, int divisor) {
int numbers = 0;
for (int i = start; i <= stop; i++)
if ((i % divisor) == 0)
numbers++
return numbers;
}
答案 2 :(得分:0)
你应从count
开始0
并相应增加。
public static int countDivisible(int start, int stop, int divisor) {
int count = 0;
for (int i = start; i <= stop; i++)
if ((i % divisor) == 0)
count++;
return count;
}
答案 3 :(得分:0)
你的countDivisible是错误的..它必须累积条件满足标准的时间
i%divisor == 0
public static int countDivisible(int start, int stop, int divisor) {
int sum = 0;
for (int i = start; i <= stop; i++) {
if ((i % divisor) == 0) {
sum++;
System.out.println(i + " is divisible by 4");
}
}
return sum;
}
答案 4 :(得分:0)
是的,我已将numbers
初始化为0,并将numbers = i / divisor;
替换为numbers++;
,现在它可以正常运行,谢谢。
public static int countDivisible(int start, int stop, int divisor) {
int numbers = 0;
for (int i = start; i <= stop; i++)
if ((i % divisor) == 0)
numbers++;
return numbers;
}