C语言,输出杨辉三角

来源:互联网 发布:淘宝刷到单如何赚钱 编辑:程序博客网 时间:2024/04/30 21:45

#include "stdio.h"
#include "stdlib.h"

 

void yanghui_num(int * yanghui, int n);
int yh_one_num(int n, int i);

 

int main(void)
{
    int n;
    inti,j;
   printf("请输入要输出杨辉三角的行数:");
    scanf("%d",&n);

    char *space = (char *)malloc(sizeof(char) * (n * 2 + 1));
    if(space ==NULL)
       exit(1);
    for(i = 0; i< n * 2; i++)
       *(space + i) = ' ';
    *(space + i)= '\0';

    int *yanghui = (int *)malloc(sizeof(int) * (n + 1));
 

    for(i =0; i < n; i++)
    {
       yanghui_num(yanghui, i);
       printf("%s", space + i * 2);
       for(j = 0; j <= i; j++)
           printf("-  ",*(yanghui + j));
       printf("\n");
    }

   free(space);
   free(yanghui);
    space =NULL;
    yanghui =NULL;

    return0;
}

 

void yanghui_num(int * yanghui, int n)
{
    int i;
    for(i = 0; i<= n; i++)
       *(yanghui + i) = yh_one_num(n, i);
}

 

int yh_one_num(int n, int i)
{
    intnumerator = 1, denominator = 1;
    int j;
    if(i ==0)
       return 1;
    for(j = 0; j< i; j++)
    {
       numerator *= (n - j);
       denominator *= (j + 1);
    }
    returnnumerator / denominator;
}

0 0