gpt4 book ai didi

java - 我正在尝试打印出二维数组的右下三角形

转载 作者:行者123 更新时间:2023-11-30 10:16:00 24 4
gpt4 key购买 nike

我试图打印出二维数组的右下角三角形,但我得到的元素三角形倒转了:

int[][] a3 = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16},
};
System.out.println("Lower right triangle");
for (int row = 0 ; row < a3.length ; row++){
for (int col = 3 ; col >= a3[0].length-row-1 ; col--) {

System.out.print("\t" + a3[row][col]);
}
System.out.println();
}

输出看起来像这样:

4
8 7
12 11 10
16 15 14 13

代替:

             4
7 8
10 11 12
13 14 15 16

最佳答案

这是给你的解决方案。尝试理解其中的逻辑,如有任何疑问,请提出。希望对你有帮助

for (int row = 0 ; row < a3.length ; row++){
for (int col = 0 ; col < a3[0].length ; col++) {
if(col>=a3[0].length-1-row){
System.out.print(a3[row][col]+"\t");

} else {
System.out.print("\t");
}
}
System.out.println();
}

关于java - 我正在尝试打印出二维数组的右下三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50195575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com