输出杨辉三角(C++和 JAVA版 )
C++版本:
#include
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
{
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<
}
cout<
}
for(int q = 0; q < n; q++)
{
delete []a[q];
}
delete []a;
}
}
效果:
JAVA版:
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
{
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();
}
}
}
效果: