Java for循环错误,或方程式错误。在if语句之后我需要写什么?
我刚开始在大学的netbeans学习java。我已经编写了一个代码,将4到30之间的数字乘以3,这样我的代码将只打印出>=到4的数字,并且在乘以3时不会超过30 我希望我的代码打印出来Java for循环错误,或方程式错误。在if语句之后我需要写什么?,java,Java,我刚开始在大学的netbeans学习java。我已经编写了一个代码,将4到30之间的数字乘以3,这样我的代码将只打印出>=到4的数字,并且在乘以3时不会超过30 我希望我的代码打印出来有7个大于或等于的整数…等等但我的代码打印出来有11个整数我总是搞不清楚在for或while循环之后我需要写什么,我很确定我的数学是正确的,但为什么它要计算到11而不是7 public static void main(String[] args) { int start = 4, stop = 30, m
有7个大于或等于的整数…等等
但我的代码打印出来有11个整数
我总是搞不清楚在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);
}
publicstaticvoidmain(字符串[]args){
int start=4,stop=30,倍数=3;
计数倍数(开始、停止、倍数);
}
公共静态无效计数倍数(整数开始、整数停止、整数倍数){
整数=0;
对于(int i=start;ipublicstaticvoidcountmultiples)(int start、int stop、int multiples){
整数=0;
对于(inti=start;i基本上,您在if中所做的是
- 首先,您将与从0开始的数字相乘,相乘后的总体结果是如果循环内部的if条件存在逻辑错误,您只需将
i*multiple
相乘即可获得预期结果:
for(int i = start; i <=stop; i++){
if(i * multiple <= stop){
numbers++;
}
}
for(int i=start;i您错过了这里的逻辑if(number*multiple好的,首先,4和30不包括在内,对吗?
因此,当设置i
时,向其添加1。
然后,在循环条件下,删除等号,使其在达到数字30之前停止
for(int i = start+1 ; i <stop; i++){//start checking from number 5 , remove the equal sign
if(multiple* i < stop){ //also remove the equal sign here
numbers++;
System.out.println(multiple* i+" :there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
}
for(int i=start+1;i)您有一个输入错误-更改if(number*multiple我想您想要i*multipleif(number*multiple
if(i*multiple <=stop)
numbers++;
for(int i = start; i <=stop; i++){
if(i * multiple <= stop){
numbers++;
}
}
for(int i = start; i <=stop; i++)
if(i * multiple <= stop)
numbers++;
for(int i = start+1 ; i <stop; i++){//start checking from number 5 , remove the equal sign
if(multiple* i < stop){ //also remove the equal sign here
numbers++;
System.out.println(multiple* i+" :there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
}