英文:
How to Flip the triangle?
问题
如何翻转这个三角形?
我制作了一个算术序列三角形。它是颠倒的。
如何将它旋转180度?
例如:
<pre>
1=1
1+2=3
1+2+3=6
等等...
</pre>
我的代码:
package javaapplication4;
public class NewClass5 {
public static void main(String[] args) {
int i=5,a;
for(int j=i; j>=1; j--) {
for(a=1; a<=i; a++)
System.out.print(a + " + ");
int n = 0;
for(a = 1; a<=i; a++) {
n = n + a;
}
System.out.print(" = "+ n);
System.out.println();
i--;
}
}
}
<details>
<summary>英文:</summary>
[How to flip this triangle?][1]
[1]: https://i.stack.imgur.com/FCE5G.png
So i was making aritmethic sequance triangle. It was upside down.
How do I turn it 180 degree?
for example:
<pre>
1=1
1+2=3
1+2+3=6
etc...
</pre>
my code:
package javaapplication4;
public class NewClass5 {
public static void main(String[] args) {
int i=5,a;
for(int j=i; j>=1; j--) {
for(a=1; a<=i; a++)
System.out.print(a +" + ");
int n = 0;
for(a = 1; a<=i; a++) {
n = n + a;
}
System.out.print(" = "+ n);
System.out.println();
i--;
}
}
}
</details>
# 答案1
**得分**: 0
我认为你只需要将循环的顺序从降序改为升序,其余部分应保持不变:
```java
for (int i = 1; i <= 5; i++) {
int sum = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
sum += j;
}
System.out.println(sum);
}
当我运行这段代码时,我能够看到预期的输出:
src: $ java NewClass5
1=1
1+2=3
1+2+3=6
1+2+3+4=10
1+2+3+4+5=15
英文:
I think you just need to change the sequence of loop from descending to ascending, rest of the things should be the same:
for (int i = 1; i <= 5; i++) {
int sum = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
sum += j;
}
System.out.println(sum);
}
When I run this, I'm able to see expected output:
src : $ java NewClass5
1=1
1+2=3
1+2+3=6
1+2+3+4=10
1+2+3+4+5=15
答案2
得分: 0
你可以针对任何 n 进行操作,通过从用户获取输入。
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
int add = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
add += j;
}
System.out.println(add);
}
英文:
You can do it for any n, by getting input from the user
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
int add = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
add += j;
}
System.out.println(add);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论