c++ - 如何在帕斯卡三角形中整合一行?

标签 c++ arrays c++11 visual-c++ multidimensional-array

我有一个最大行数为 5 的帕斯卡三角形。假设我想找到第四行的积分。如何访问帕斯卡三角形的第四行。 更准确地说,我想知道如何通过输入行号 n 来访问 pascal 三角形中的一行

Code

#include <iostream>

using namespace std;

int main(){

    int a1, a2, a3, a4, a5, pascal, columns;
    const int rows = 5;

    int **array = new int *[rows]; //generating array
    for(int i = 0; i <= rows; i++)
    array[i] = new int [columns];

    for (int i = 0; i <= rows; i++){  //loop for te pascal's triangle
        for (int j = 0; j <= i; j++){
            if(j == 0 || i == 0){
                pascal = 1;  //first element of pascal's triangle
            }
            else{
                pascal = pascal *(i - j + 1) / j; //pascal's triangle formula
            }
            cout << "  " << pascal; // printing pascals triangle
         }
         cout << "\n";
    }
    cout << "enter which row to integrate: ";
    // here I want to directly access a row rather that entering the elements of the row 
    cin >> a1;
    cin >> a2;
    cin >> a3;
    cin >> a4;
    cin >> a5;

 }

1
1 1
1 2 1
1 3 3 1 ------> like of n = 4 我想整合这一行的元素
1 4 6 4 1

And the answer should be for 1,3,3,1 = 0, 1, 1.5, 1, 0.25

最佳答案

你应该首先用元素填充数组然后你可以像这样访问它们(编辑:确保初始化列变量,我将它设置为 5)

#include <iostream>

using namespace std;

int main() {

    int row_nb, pascal, columns = 5; //Initialized columns with columns = 5 
    const int rows = 5;

    int **array = new int *[rows]; //generating array
    for (int i = 0; i <= rows; i++)
        array[i] = new int[columns];

    for (int i = 0; i <= rows; i++) {  //loop for te pascal's triangle
        for (int j = 0; j <= i; j++) {
            if (j == 0 || i == 0) {
                pascal = 1;  //first element of pascal's triangle
            }
            else {
                pascal = pascal *(i - j + 1) / j; //pascal's triangle formula
            }
            array[i][j] = pascal; //fill the array
            cout << "  " << pascal; // printing pascals triangle
        }
        cout << "\n";
    }
    cout << "enter which row to intergrate: ";
    // here I want to directly access a row rather that entering the elements of the row 
    cin >> row_nb; //input the row you want to access

    for (int i = 0; i <= row_nb; i++) { //access the elements in this row in the array
    cout << array[row_nb][i] << " ";
}
    return 0; // add the return statement since the return type of the main function is int
}

关于c++ - 如何在帕斯卡三角形中整合一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53139557/

相关文章:

C++ 标准 - 如何处理 "array of unknown bound of T"

c++ - 将 union 枚举传递到 C++ 中的函数中

c++ - 如何使用 Boost::Python 包装 C++ OpenCV 代码?

javascript - 我可以保存一个文件,该文件将仅使用 javascript/C/C++ 在服务器端从 php 代码生成,并且没有打开浏览器吗?

java - Java方法签名后奇怪的 "[]"

c++ - 可以将特化注入(inject) std 命名空间吗?

c++ - 如何更新 std::vector<pair<int, int>> 中最近输入的元素?

ruby-on-rails - 如何在 JSON 中获取对象数组的某些属性

performance - C++11 move 语义与指针 - 性能测量

c++ - SFINAE enable_if 显式构造函数