我正在努力创造三角形。但是,我真的发现这个难以实现。你能给我一个完成它的方法吗?
5
545
54345
5432345
543212345
OPS!你太难了你投票很多! 这是我试图做的事情的代码,但唯一真实的是空间的计算。
for (int i = 1; i <= n; i++) {
for (int j = n; j > i; j--) {
System.out.print(" ");
}
//left
for (int j = i; j > 1; j--) {
System.out.print(j + " ");
}
//right
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
答案 0 :(得分:3)
寻找一些模式。
第1行以4(5-1)个空格开头。第2行有3个空格......最后一行没有空格。
第1行只有最高数字一次。第2行有最高,第二高,最高。最后一行以最高行开头,并打印到1,然后返回到最高行。
如果你编写代码来处理这些一般情况,那么它可能会起作用。
答案 1 :(得分:1)
我希望这个简单的算法能让您了解如何逐步解决这个问题。
int n = 5;
// We go line by line
for (int line=0; line<n; line++) {
// Calculate number of spaces in the line. Number of spaces on the
// right hand side is always the same as the number on the left hand side
int spaces = n - line;
// We have twice as much digits in each line as the line index plus one
// digit (because we always have an odd number of digits).
int digits = 2*line + 1;
// Print left spaces
for (int i=0; i<spaces; i++) {
System.out.print(" ");
}
// Print digits. This does the trick.
for (int i=0; i<digits; i++) {
// The key for the algorithm is this symmetrical triangle. We will use
// digits/2 - i expression, which prints out the following triangle
// 0
// 1,0,-1
// 2,1,0,-1,2
// etc.
//
// Now we need to get rid of minus sign by using Math.abs function
// and add number of spaces decreasing with every new line and
// compensating increasing digits in the triangle.
System.out.print(spaces + Math.abs(digits/2 - i));
}
// Print right spaces. We may omit this, as right spaces are not
// visible and they have no impact on the shape.
for (int i=0; i<spaces; i++) {
System.out.print(" ");
}
// Finish the line
System.out.println();
}
答案 2 :(得分:0)
你走了:
def makeTriangle(n):
for i in range(n):
print(" "*(n-i), end="")
for j in range(0, i):
print(n-j, end="")
for j in range(i, -1, -1):
print(n-j, end="")
print(" "*(n-i))
我已经测试了上面的代码,它运行得很完美。