21xrx.com
2024-09-08 11:35:29 Sunday
登录
文章检索 我的文章 写文章
学习C语言 编写杨辉三角前十行
2023-06-15 21:19:05 深夜i     --     --
C语言 编程 杨辉三角 循环 数组

杨辉三角是数学上的一种经典图形,它也可以用编程语言来实现。在本文中,我们将介绍如何使用C语言编写杨辉三角前十行。

杨辉三角是一种由数字排列成三角形的图形,其中每个数字都等于上方两个数字之和。在编写C语言代码时,我们可以用二维数组来表示这个图形。在循环中,我们可以用if语句来计算每个数字的值,并将它们存储在数组中。最后,我们可以使用循环嵌套来打印出这个三角形。

以下是完整的C语言代码:


#include

int main()

{

  int rows, coef = 1, space, i, j;

  printf("Enter the number of rows: ");

  scanf("%d",&rows);

  for(i=0; i

  {

    for(space=1; space <= rows-i; space++)

      printf(" ");

    for(j=0; j <= i; j++)

    {

      if (j==0 || i==0)

        coef = 1;

      else

        coef = coef*(i-j+1)/j;

      printf("%4d", coef);

    }

    printf("\n");

  }

  return 0;

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复