纵有疾风起
人生不言弃

输出杨辉三角(C++和 JAVA版 )

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; 
		}

}

效果:

输出杨辉三角(C++和 JAVA版 )插图

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<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();
			
		}
			
	}

}

效果:

输出杨辉三角(C++和 JAVA版 )插图1

原文链接:https://blog.csdn.net/w605283073/article/details/44818019

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

未经允许不得转载:起风网 » 输出杨辉三角(C++和 JAVA版 )
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录