输出杨辉三角(C++和 JAVA版 )
C++版本:#include <iostream>
using namespace std;
void main()
{
int n=10;
while(n!=-1)
{
cout<<"请输入 杨辉三角 行数:";
cin>>n;
int **a = new int* ;
for(int m = 0; m < n; m++)
{
a = new int ;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
if(j==0||i==j)
{
a = 1;
}else
{
a = a+a;
}
cout<<a<<"\t";
}
cout<<endl;
}
for(int q = 0; q < n; q++)
{
delete []a;
}
delete []a;
}
}
效果:
JAVA版:import java.util.Scanner;
/**
* 杨辉三角JAVA版
* @author 明明如月
* QQ605283073
*/
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;
for(int i=0;i<input;i++)
{
for(int j=0;j<=i;j++)
{
if(j==0||j==i)
{
arr = 1;
}else
{
arr = arr+arr;
}
System.out.print(arr+"\t");
}
System.out.println();
}
}
}catch(Exception e)
{
e.printStackTrace();
}finally
{
in.close();
}
}
}
效果:
文档来源:51CTO技术博客https://blog.51cto.com/u_15316467/3309027
页:
[1]