我想打印一个三角形/金字塔样式,比如:
1
323
54345
7654567这是我的代码:
int lines = 5;
for (int i = 1; i < lines; i++) {
for (int j = 1; j < lines-i; j++) {
System.out.print(" ");
}
for (int j = i; j > 1; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
for (int j = i; j < i+i; j++) {
System.out.print(j);
}
System.out.println();
}我得到的是
1
223
32345
4324567在办公室工作的时候,我一直在学习代码,我想一周以来,我仍然找不到解决这个问题的办法,即使我在谷歌上使用搜索。我只喜欢通过条件来增强我的逻辑,还没有大量的面向对象或递归。
发布于 2015-01-06 14:55:42
第一个循环中的问题就是你在第二个循环中发现的问题!(这与循环中最大的数字有关)
for (int j = i; j > 1; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}看看金字塔左边的数字。它们从右端的位置开始(金字塔的每条线都是对称的)。这个数字的一般公式是i + i - 1,其中i是来自外部循环的行号。
第二行从2 * i - 1 = 2 * 2 - 1 = 3开始。第三行从2 * 3 - 1 = 5等开始。
因此,第二个内环应该如下所示:
for (int j = i + i - 1; j > i; j--) {
System.out.print(j);
}发布于 2015-01-06 16:45:03
int线= 4;
(int i= 1;i <=行;i++) {
for (int j = 1; j < lines-i+1; j++) {
System.out.print(" ");
}
//replace this
for(int j=0; j<i-1; j++) System.out.print(i*2-j-1);
System.out.print(i);
for(int j=; j<i-1;j++) System.out.print(i+j+1);
//==========
System.out.println();}
https://stackoverflow.com/questions/27801076
复制相似问题