[英]Java: Having trouble printing out this pyramid-like reversed number pattern
我需要知道如何打印出以下模式:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
任何和所有的幫助表示贊賞。 到目前為止我所擁有的是:
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
for (int i = num-1; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
它輸出這個:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
所以我理解了模式本身的結構,但似乎我需要以某種方式逆轉流程。 這是我不明白的。
更改循環條件,如下所示:
public class Main {
public static void main(String[] args) {
int num = 5;
for (int i = num; i >= 1; i--) {// Start with num and go downwards up to 1
for (int j = i; j <= num; j++) {// Start with i and go upwards up to num
System.out.print(j + " ");
}
System.out.println();
}
for (int i = 2; i <= num; i++) {// Start with 2 and go downwards up to num
for (int j = i; j <= num; j++) {// Start with i and go downwards up to num
System.out.print(j + " ");
}
System.out.println();
}
}
}
輸出:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
接受的答案不輸出正確的模式,所以......這段代碼有效。
有兩個循環,每個循環逐行迭代。 第一個從 5 到 1,第二個從 2 到 5。
在每次迭代中(每行)將在第一個數字旁邊打印以下數字。
int num = 5;
for(int i = num ; i > 0 ; i--){
System.out.print(i+" "); //Print the first number of the line
for(int j = 1; j <= num-i; j++){
//Print as extra number as line need (first line = 0 extra numbers,
//second line = 1 extra number...)
System.out.print((i+j)+" ");
}
System.out.println(); //New line
}
for (int i = 2; i <= num; i++) { //Print second part starting by 2
for (int j = i; j <= num; j++) { //Print extra numbers
System.out.print(j+" ");
}
System.out.println(); //New line
}
輸出符合預期:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.