我刚刚开始在大学学习java netbeans。我编写了一个代码,将4到30之间的数字乘以3,这样我的代码只打印出数字> = 4,乘以3时不会超过30。
我希望我的代码打印出there are 7 integers greater or equal....etc
,但我的代码打印出来there are 11 integers
我总是对我在for或while循环后需要写的东西感到困惑,我很确定我的数学是对的,但为什么计算到11而不是7?
public static void main(String[] args) {
int start = 4, stop = 30, multiple = 3;
countMultiples(start,stop, multiple);
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++)
if(numbers * multiple <= stop)
numbers++;
System.out.println("there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
System.out.println("which multiplied by " + multiple);
}
答案 0 :(得分:1)
如果for循环中的条件你有逻辑错误,你只需要乘以i * multiple
以获得预期的结果:
for(int i = start; i <=stop; i++){
if(i * multiple <= stop){
numbers++;
}
}
答案 1 :(得分:0)
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++) {
if (i * multiple <= stop) { // <-- the numbers should be i
numbers++;
} else {
break;
}
}
}
答案 2 :(得分:0)
基本上你在if里面做的是
*您在计算中得到的差异是因为您从0开始,但正如您所提到的,您的号码应该从4开始。
所以而不是
if(numbers * multiple <= stop)
numbers++;
这样做
if(i*multiple <=stop)
numbers++;
从现在开始,你的初始值为4,你得到了正确的数量
答案 3 :(得分:0)
你错过了这里的逻辑if(numbers * multiple <= stop)
这样做
for(int i = start; i <=stop; i++)
if(i * multiple <= stop)
numbers++;
答案 4 :(得分:0)
好的,首先,4和30不包括在内吗?
所以在设置Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed May 10 10:54:16 CEST 2017
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "/nicinc/login/login", template might not exist or might not be accessible by any of the configured Template Resolvers
时添加1。
然后在循环的条件下删除等号,所以它会在到达数字30之前停止。
i