java数组的应用:杨辉三角和回形数
程序员文章站
2022-11-30 15:35:31
杨辉三角代码:public class ArrayDemo02 { public static void main(String[] args) { int yanggui[][] = new int[9][]; for(int i = 0;i < yanggui.length;i++){ yanggui[i] = new int[i + 1]; yanggui[i][0] = yanggui[i][i] =...
杨辉三角
代码:
public class ArrayDemo02 {
public static void main(String[] args) {
int yanggui[][] = new int[9][];
for(int i = 0;i < yanggui.length;i++){
yanggui[i] = new int[i + 1];
yanggui[i][0] = yanggui[i][i] = 1;
if(i > 1){
for(int j = 1;j < yanggui[i].length - 1;j++){
yanggui[i][j] = yanggui[i - 1][j] + yanggui[i - 1][j - 1];
}
}
}
for(int i = 0;i < yanggui.length;i++){
for(int j = 0;j < yanggui[i].length;j++){
System.out.print(yanggui[i][j] + "\t");
}
System.out.println();
}
}
}
回形数
代码
public class learn {
public static void main(String[] args){
System.out.println("请输入你需要打印多少阶的回形数:");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt(); // 接收num,则打印num阶的回形数
scan.close();
int[][] hui = new int[num][num];
for(int i = 0,j = 0,flag = 0,theNum = 1; theNum<=(num*num);) { // i可视为二维数组的第i+1排,j可视为二维数组的j+1列;flag表示回形数进行的第flag+1圈;theNum为赋的值。
if(j<num-flag) { //回形数向右走时
hui[i][j] = theNum;
j++;
theNum++;
}
else if(i+1<num-flag) { //回形数向下走时
hui[i+1][j-1] = theNum;
theNum++;
i++;
}
else {
for(int m = num-flag-1,n = num -flag-1;;) {
if(n>flag) { //回形数向左走时
n--;
hui[m][n] = theNum;
theNum++;
}
else if(m>flag+1) { //回形数向右走时
m--;
hui[m][n] = theNum;
theNum++;
}
else {
i = flag+1;
j = flag+1;
flag++;
break;
}
}
}
}
for(int a = 0;a<num;a++) {
for(int b = 0;b<num;b++) {
System.out.printf("%d ",hui[a][b]);
}
System.out.println("\n");
}
}
}
本文地址:https://blog.csdn.net/qq_43141726/article/details/107282992
上一篇: 学习java的第9天
下一篇: 网站被劫持到其它网站如何解决