打印杨辉三角
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
找图形规律:
1.每一列的第一个和最后一列都是1(行列相等)
2.每一行,列数,和当前的行数相同
3.a [row] [col] = a[row-1] [col-1]+a[row-1][col]
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[10][10] = { 0 };
int row, col;
for (row = 1; row <=5; row++){
for (col = 1; col <= row; col++){
if (col == 1 || col == row){
a[row][col] = 1;
}
else{
a[row][col] = a[row - 1][col - 1] + a[row - 1][col];
}
printf(" %d ", a[row][col]);
}
printf("\n");
}
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
void PrintYanghui(int N){
int a[10][10] = { 0 };
int row, col;
for (row = 1; row <=N; row++){
for (col = 1; col <= row; col++){
if (col == 1 || col == row){
a[row][col] = 1;
}
else{
a[row][col] = a[row - 1][col - 1] + a[row - 1][col];
}
printf(" %d ", a[row][col]);
}
printf("\n");
}
}
int main(){
PrintYanghui(5);
system("pause");
return 0;
}
运行结果:
这个方法是首先个第一行第一列的赋值1,后面的依次进行相加即可,假如a[0][1]对于杨辉三角来说没有那么计算时按照0,进行相加即可
#include <stdio.h>
#include <stdlib.h>
void Print(int arr[][20],int n) { //二维数组
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void Yanghui(int n) {
int arr[20][20] = { 0 };
int i, j;
for (int i = 0; i < n;i++) {
arr[i][0] = 1;
for (int j = 1; j <= i; j++) {
arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
}
}
Print(arr, n);
}
int main () {
Yanghui(10);
system ("pause");
return 0;
}
杨辉三角的应用
1.杨辉三角与多项式求系数(a + b)^n
(a+b) ^ 1 = a + b
(a+b) ^ 2 = a ^ 2 + 2 ab + b ^ 2
(a+b) ^ 3 = a ^ 3 + 3 * a ^ 2 b + 3 * b ^ 2 * a + b ^ 3
(a+b) ^ 4 = a ^ 4 + 4 * a ^ 3 b + 6 * a ^ 2 * b ^ 2 + 4 * b ^ 3 + b ^ 4
.
.
依次类推能够很明显的得到对应次方的不同系数不用,而系数恰好是杨辉三角的行数所对应的系数,因此能够将其转化为杨辉三角进行计算(杨辉三角的行数等于多项式的次方)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void Print(int arr[][20], int n) { //二维数组
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void PrintYanghui(int n) {
int arr[20][20] = { 0 };
int i, j;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (j == 1 && j == i) {
arr[i][j] = 1;
}
else {
arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
}
}
}
Print(arr, n);
}
int main() {
int n = 0;
printf("请输入表达式[(a + b^n]n次方的的系数: ");
scanf("%d",&n);
PrintYanghui(n);
system("pause");
return 0;
}