杨辉三角形(c && java)
程序代码:
#include <stdio.h> int main(void) { int n, i, j, spaces; if(!scanf("%d", &n) || n < 1) { printf("Unsupported operation!\n"); return -1; } spaces = ((n++) - 1) * 4; int array[n][n]; for(i = 0; i < n; i++) for(j = 0; j < n; j++) array[i][j] = 0; array[0][0] = 1; for(i = 1; i < n; i++) for(j = 1; j < n; j++) array[i][j] = array[i - 1][j - 1] + array[i - 1][j]; for(i = 1; i < n; i++) { for(j = 0; j < spaces; j++) putchar(' '); for(j = 1; j < i + 1; j++) printf("%-8d", array[i][j]); spaces -= 4; printf("\n"); } return 0; }
以上代码要编译必须要支持C99。
程序代码:
import java.util.Scanner; public class Triangle { public static void main(String[] args) { int n, i, j, spaces; Scanner input = new Scanner(System.in); if((n = input.nextInt()) < 1) { System.out.printf("Unsupported operation!\n"); System.exit(1); } spaces = ((n++) - 1) * 4; int[][] array = new int[n][n]; array[0][0] = 1; for(i = 1; i < n; i++) for(j = 1; j < n; j++) array[i][j] = array[i - 1][j - 1] + array[i - 1][j]; for(i = 1; i < n; i++) { for(j = 0; j < spaces; j++) System.out.printf(" "); for(j = 1; j < i + 1; j++) System.out.printf("%-8d", array[i][j]); spaces -= 4; System.out.println(); } } }