21xrx.com
2025-03-31 18:11:07 Monday
文章检索 我的文章 写文章
使用数组编写C++版本的杨辉三角实现方法
2023-07-05 09:34:15 深夜i     35     0
C++ 数组 杨辉三角

杨辉三角是指一个由数字组成的三角形,其中每个数字是它上方两个数字的和。在数学中,杨辉三角也被称为帕斯卡三角形,因为它是数学家Blaise Pascal在17世纪中发现的。在计算机编程中,我们可以使用数组来编写C++版本的杨辉三角实现方法。

要编写杨辉三角的C++程序,我们需要先定义一个二维数组来存储所有的数字。我们可以使用一个for循环来遍历所有的行和列,并在每个位置上计算和存储数字。为了避免数组越界,我们需要在数组的第一行和第一列上赋值为1。

以下是一个使用数组编写的C++版本的杨辉三角实现方法:

#include <iostream>
using namespace std;
int main()
{
  int num_rows;
  cout << "Enter the number of rows you wish to see in Pascal’s triangle: ";
  cin >> num_rows;
  int triangle[num_rows][num_rows];
  // Initialize first row and first column to 1
  for (int i = 0; i < num_rows; i++){
    triangle[i][0] = 1;
    triangle[0][i] = 1;
  }
  // Fill the rest of the triangle
  for (int i = 1; i < num_rows; i++){
    for (int j = 1; j < num_rows; j++){
      triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
    }
  }
  // Print the triangle
  for (int i = 0; i < num_rows; i++){
    for (int j = 0; j <= i; j++){
      cout << triangle[i][j] << " ";
    }
    cout << endl;
  }
  return 0;
}

在上面的程序中,我们首先让用户输入需要显示多少行的杨辉三角。然后,我们定义了一个二维数组来存储杨辉三角中所有数字的值。接下来,我们通过两个for循环来遍历所有的行和列,并对每个位置上的数字进行计算和存储。

最后,我们再次使用两个for循环来打印出整个杨辉三角。每行数字之间都用空格隔开,并在行末输出换行符。

在完成以上步骤之后,我们就能够使用数组成功地编写C++版本的杨辉三角实现方法。

  
  

评论区

请求出错了