当我输入6,8,16或者24的时候为什么不能正确输出
public class lala {
public static void main (String[] args){
int s;
Scanner in =new Scanner(System.in);
System.out.print("请输入一个正整数:");
s=in.nextInt();
new teee(s);
}
}
class teee{
int x=6,y=8;
public teee(int s){
System.out.print("结果:");
int i,j,m=-1;
for(i=0;i*x<s;i++){
for(j=0;j*y<s;j++){
if(s==i*x+j*y){
m=i+j;
System.out.println(m);
break;
}
}
if(m>0)break;
}
if(m<0){System.out.println(m);}
}
}
From the code point of view, let’s regard the question’s code as finding the solution that satisfies the equation s = 6i+8j, has the smallest value of i, and outputs i+j.
First of all, it can be determined intuitively. If you want to satisfy the situation of i=0 or j=0, the judgment conditions of the two loops should be set to
Otherwise, we cannot get the solution of i=0 or j=0, that is, the integer multiple solution, which is why the 6, 16, and 24 you mentioned are inaccurate.
Separating line:
It is still difficult to choose between the activity level of the forum and the quality of the forum’s Q&A.
Personally, I have always felt that there is no need to write answers or comments that only criticize without suggestions, such as "This kind of question is very simple", "You can find it on Baidu", etc. It is purely to cause trouble for others. For newcomers, this kind of problem may not be simple. In addition, Baidu does not have such specific code logic problems.
If new people ask questions that are not standardized, you can point them out and guide them to adopt the correct questioning posture. This will not only prevent them from making such mistakes in the future, but also will not dampen the enthusiasm of new people and ensure the activity of the forum. Our forum can be more active. friendly.
Recommended topic reference:
https://segmentfault.com/tour
I am also new here. I don’t know if segmentfault has a watering park for newbies. Maybe I can ask simple questions here, problem solved.
Debug, see if there is something wrong with the output of -1? Neither meets the conditions of the for loop. You want to output if(s==ix+jy){