C++版本:
#include <iostream> using namespace std; void main() { int n=10; while(n!=-1) { cout<<"请输入 杨辉三角 行数:"; cin>>n; int **a = new int* [n]; for(int m = 0; m < n; m++) { a[m] = new int [n]; } for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { if(j==0||i==j) { a[i][j] = 1; }else { a[i][j] = a[i-1][j-1]+a[i-1][j]; } cout<<a[i][j]<<"\t"; } cout<<endl; } for(int q = 0; q < n; q++) { delete []a[q]; } delete []a; } }
效果:
import java.util.Scanner; /** * 杨辉三角 JAVA版 * @author 明明如月 * QQ 605283073 */ public class YangHui { public static void main(String []args) { int input = 0; int arr[][]=null; Scanner in = new Scanner(System.in); try { while(in.hasNextInt()) { input = in.nextInt(); arr= new int[input][input]; for(int i=0;i<input;i++) { for(int j=0;j<=i;j++) { if(j==0||j==i) { arr[i][j] = 1; }else { arr[i][j] = arr[i-1][j]+arr[i-1][j-1]; } System.out.print(arr[i][j]+"\t"); } System.out.println(); } } }catch(Exception e) { e.printStackTrace(); }finally { in.close(); } } }
效果:
原文地址:http://blog.csdn.net/w605283073/article/details/44818019