用java创建三角形
我试着练习创建三角形。然而,我确实发现这很难实现。你能给我一个完成它的方法吗用java创建三角形,java,Java,我试着练习创建三角形。然而,我确实发现这很难实现。你能给我一个完成它的方法吗 5 545 54345 5432345 543212345 行动!你太强硬了。你投了很多票! 这是我试图做一些事情的代码,但唯一正确的事情是计算空间 for (int i = 1; i <= n; i++) { for (int j = n; j > i; j--) { System.out.print(" "); } //left
5
545
54345
5432345
543212345
行动!你太强硬了。你投了很多票!
这是我试图做一些事情的代码,但唯一正确的事情是计算空间
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();
}
for(int i=1;i;j--){
系统输出打印(“”);
}
//左
对于(int j=i;j>1;j--){
系统输出打印(j+“”);
}
//对
对于(intj=1;j寻找一些模式
第1行以4(5-1)个空格开始。第2行有3个空格…最后一行没有空格
第1行只有一次最高的数字。第2行有最高、第二高、最高。最后一行从最高开始,向下打印到1,然后返回到最高
如果您编写代码来处理这些一般情况,那么它可能会工作。给您:
def makeTriangle(n):
对于范围(n)中的i:
打印(“*(n-i),end=”“)
对于范围(0,i)内的j:
打印(n-j,end=“”)
对于范围(i,-1,-1)内的j:
打印(n-j,end=“”)
打印(“*(n-i))
我已经测试了上面的代码,它工作得很好。我希望这个简单的算法能让您了解如何一步一步地解决这个问题
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();
}
int n=5;
//我们一行一行地走
对于(int line=0;line此问题似乎与主题无关,因为它是一个代码编写请求。您是否编写了任何代码?不,我没有编写代码的请求。我想讨论一下我可以实现的方式。请向我们展示您已经尝试了一些东西,我们将帮助您更正错误!给我们证明您已经做出了努力。您将如何继续rt?写伪代码,或者写几个段落来说明如何逻辑地完成它。或者至少,它在…中工作得很好。我更新了代码,它打印为12132123。我想问题在限制范围内,我如何更改?我找不到545,在下一行54345。编辑:我编辑了我的代码。我更新了代码,它打印为12132123。我想问题出在哪里在极限内,我如何改变?