本文目錄一覽:
java編寫楊輝三角~~~
楊輝三角線的推理:
楊輝三角形性質:
每行數字左右對稱,由 1 開始逐漸變大,然後變小,回到 1。
第 n 行的數字個數為 n 個。
第 n 行數字和為 2^(n-1) 。
每個數字等於上一行的左右兩個數字之和。可用此性質寫出整個楊輝三角形。
第 n 行的第 1 個數為 1,第二個數為 1× (n-1) ,第三個數為 1× (n-1) × ( n-2) /2,第四個數為 1× (n-1) × (n-2) /2× (n-3) /3…依此類推。
算法原理:
使用一個二維數組 yh[][] 存儲楊輝三角形的數據,行和列的大小為所需要輸出的行數 Row(本程 序中 Row 為 10)。
使用 for 循環使楊輝三角中除了最外層(不包括楊輝三角底邊)的數為 1 ;
使用語句 yh[i][j] = yh[i – 1][j – 1] + yh[i – 1][j] 使第 i 行第 j 列的數據等於第(i-1) 行
第(j-1)列的數據與第(i-1)行第(j)列的數據之和,即每個數字等於上一行的左右兩個數字之和。
代碼的實現
package com.practice;
public class YangHuiSanJiao
{
public static void main(String[] args) {
int [][]a = new int [10][10];
for(int n = 0; n 10;n++)
{
a[n][0] = 1;
a[n][n] = 1;
}
for(int n = 2; n 10; n++)
{
for(int j = 1; j n; j++)
{
a[n][j] = a[n -1][j -1] + a[n – 1][j];
}
}
for(int n = 0; n 10; n++)
{
for(int k = 0; k 2 * (10 – n) – 1; k++)
{
System.out.print(” “);
}
for(int j = 0; j = n; j++)
{
System. out.print(a[n][j] + ” “);
}
System.out.println();
}
}
}
用java編程楊輝三角的代碼?
1.楊輝三角形由數字排列,可以把它看做一個數字表,其基本特性是兩側數值均為1,其他位置的數值是其正上方的數字與左上角數值之和,下面是java使用for循環輸出包括10行在內的楊輝三角形
2.思路是創建一個整型二維數組,包含10個一維數組。使用雙層循環,在外層循環中初始化每一個第二層數組的大小。在內層循環中,先將兩側的數組元素賦值為1,其他數值通過公式計算,然後輸出數組元素。
代碼如下:
public class YanghuiTriangle {
public static void main(String[] args) {
int triangle[][]=new int[10][];// 創建二維數組
// 遍歷二維數組的第一層
for (int i = 0; i triangle.length; i++) {
triangle[i]=new int[i+1];// 初始化第二層數組的大小
// 遍歷第二層數組
for(int j=0;j=i;j++){
// 將兩側的數組元素賦值為1
if(i==0||j==0||j==i){
triangle[i][j]=1;
}else{// 其他數值通過公式計算
triangle[i][j]=triangle[i-1][j]+triangle[i-1][j-1];
}
System.out.print(triangle[i][j]+”\t”); // 輸出數組元素
}
System.out.println(); //換行
}
}
}
Java語言楊輝三角
打印楊輝三角代碼如下:
public class woo {
public static void triangle(int n) {
int[][] array = new int[n][n];//三角形數組
for(int i=0;iarray.length;i++){
for(int j=0;j=i;j++){
if(j==0||j==i){
array[i][j]=1;
}else{
array[i][j] = array[i-1][j-1]+array[i-1][j];
}
System.out.print(array[i][j]+”\t”);
}
System.out.println();
}
}
public static void main(String args[]) {
triangle(9);
}
}
擴展資料:
楊輝三角起源於中國,在歐洲這個表叫做帕斯卡三角形。帕斯卡(1623—-1662)是在1654年發現這一規律的,比楊輝要遲393年。它把二項式係數圖形化,把組合數內在的一些代數性質直觀地從圖形中體現出來,是一種離散型的數與形的優美結合。
楊輝三角具有以下性質:
1、最外層的數字始終是1;
2、第二層是自然數列;
3、第三層是三角數列;
4、角數列相鄰數字相加可得方數數列。
原創文章,作者:LNHIO,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/317494.html