用户输入
5
必需的输出(使用while循环)
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
代码:
while (temp1 <= a) {
while (temp2 <= a) {
temp = temp2 * temp1;
System.out.print(temp + " ");
temp2++;
}
temp1++;
System.out.println();
}
我正在接受a
作为输入并试图形成这个数字,但我不能......请帮助
答案 0 :(得分:3)
内部temp2
循环后while
的值为a+1
。由于您之后未将其重置为1
,因此无法再次进入此内循环,因为无法满足条件while(temp2<=a)
。要更正它,请在内循环之前或之后将temp2
设置为外部循环内的1
。
答案 1 :(得分:2)
如果我必须将问题分解为简单的话,
有很多种方法可以做到。
我想使用for循环将是最简单的。
答案 2 :(得分:1)
下面的代码注释解释了您的代码有什么问题。
//assume temp1 equals 1
while(temp1 <= a){
temp2 = 1;//you're primarily forgetting to reset the temp2 count
while(temp2 <= a){
temp = temp1*temp2;
System.out.print(temp + " ");
temp2++;
}
temp1++;
System.out.println();
}
答案 3 :(得分:1)
int a = 5;
int temp1 = 1;
int temp2= 1;
int temp = 1;
while(temp1 <= a){
while(temp2 <= a){
temp = temp2*temp1;
System.out.print(temp + " ");
temp2++;
}
System.out.println();
temp1++;
temp2=1;
}
上面的代码应该有您想要的结果。在循环结束时重置temp2变量。只需将int a = 5
更改为您想要的任何内容即可。
补充答案:
int userInput = 5;
int answer = 0;
for(int y = 0; y < userInput; y++){
for(int x = 0; x < userInput; x++ ){
answer = x * y;
System.out.print(answer + " ");
}
System.out.println();
}
使用此答案,您无需重置临时变量并将产生所需的结果
答案 4 :(得分:1)
int a = 5; //Or however else you get this value.
//Initialize your values
int temp1 = 1;
int temp2 = 1;
int temp; //Only need a declaration here.
while (temp1 <= a) {
while(temp2 <= a) {
temp = temp1*temp2;
System.out.print(temp + " ");
temp1++;
temp2++;
}
//This executes between inner loops
temp2 = 1; //It's important to reset
System.out.println();
}
或另一种紧凑的方式:
int a = 5;
int row = 0;
int col = 0;
while (++row <= a) {
while(++col <= a) {
System.out.print(row*col + " ");
}
col = 0;
System.out.println();
}
答案 5 :(得分:1)
for(int i=1; i<=a; i++){
System.out.print(i);
for(int j=2; j<=a; j++){
int val = i*j;
System.out.print(" " + val);
}
System.out.println();
}