21xrx.com
2024-06-03 03:41:45 Monday
登录
文章检索 我的文章 写文章
C++代码实现杨辉三角
2023-07-08 09:10:20 深夜i     --     --
C++ 杨辉三角 数组 循环 递推公式

杨辉三角是一个数字三角形,该三角形中每个数是上面两数之和,除了两侧的数为1。它是由中国南宋杨辉在13世纪发现的一种数字规律,因此得名为“杨辉三角”。

通过使用C++编程语言,我们可以很容易地生成杨辉三角。以下是实现该算法的代码:


#include <iostream>

using namespace std;

int main() {

  int numRows;

  // Ask user for number of rows

  cout << "Enter the number of rows: ";

  cin >> numRows;

  // Create the triangle

  int triangle[numRows][numRows];

  for (int i = 0; i < numRows; i++) {

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

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

      triangle[i][j] = 1;

     } else {

      triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];

     }

     cout << triangle[i][j] << " ";

   }

   cout << endl;

  }

  return 0;

}

该代码首先会要求用户输入要生成的行数,然后创建一个二维数组来存储杨辉三角中的数字。接下来,代码循环遍历每一行和每一列,将最左和最右的数字设置为1,并将其他数字设置为上一行中前一个数字和前一列中前一个数字的和。最后,代码将杨辉三角中的数字输出到屏幕上。

使用上述代码,我们可以很容易地生成任意行数的杨辉三角,从而更好地理解这个著名的数字规律。

  
  

评论区

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