簡體   English   中英

具有幾何級數的C ++用戶定義的二維數組

[英]C++ User-defined 2 dimensional array with geometrical progression

我正在通過解決不同的問題自己學習C ++。 我正在嘗試解決最初為C ++中的Pascal設計的問題。 它應該要求用戶輸入3個整數M,N和q。 然后,它應該使尺寸為MxN的2d整數數組組成,其中(I = I,... M)線的所有元素都是幾何級數的成員,第一個元素等於線(I)的數量和分母q。

我想創建一個動態質量塊,但是我意識到它實際上不能用於兩個未定義的整數。 因此,我嘗試了矢量。 我想我以正確的方式創建了它們,但是我不知道如何進行幾何級進。

這是我的代碼:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int m, n, q;

    cout << "Enter the number for M \n";
    cin >> m;
    if (cin.fail())
    {
        cin.clear();
        cin.ignore();
        cout << "This is not a number! " << endl;
        system("pause");
        return 0;
    }
    cout << "Enter the  number for N \n";
    cin >> n;
    if (cin.fail())
    {
        cin.clear();
        cin.ignore();
        cout << "This is not a number! " << endl;
        system("pause");
        return 0;
    }
    cout << "Enter the number  for Q \n";
    cin >> q;
    if (cin.fail())
    {
        cin.clear();
        cin.ignore();
        cout << "This is not a number! " << endl;
        system("pause");
        return 0;
    }
    int** matrix;
    matrix = new int*[m];
    for (int i = 0; i < m; i++)
        matrix[i] = new int[n];


    for (int i = 0; i < m; i++)
    {
        matrix[i][0] = i + 1;
    }
    for (int i = 0; i < m; i++)
    {
        for (int j = 1; j < n; j++)
        {
            matrix[i][j] = (i + 1)*pow(i, j);
            cout << matrix[i][j];

        }
    }
    system("pause");
    return 0;





}

注意:您可以創建一個大小可變的二維數組,盡管它涉及內存分配並且有點難看。

int** matrix;
matrix = new int*[M];
for (int i = 0; i < M; i++)
    matrix[i] = new int[N];

這是創建大小為MxN的數組的代碼。 不要忘記像這樣釋放內存:

for (int i = 0; i < M; i++)
    delete matrix[i];
delete matrix;

至於您關於幾何級數的問題,我不確定您要問什么。 當您說幾何級數時,您是否指的是2 10 50 250等。 我不確定您所說的“行”是什么意思,因為您沒有在代碼中引用任何此類變量。

編輯

因此,一旦創建了MxN矩陣,就可以遍歷行並初始化行,如下所示:

for (int i = 0; i < M; i++)
{
    matrix[i][0] = i+1;
}

這應將每一行的第一列設置為正確的數字。 然后,遵循此思路的東西應該填充其余的幾何級數:

for (int i = 0; i < M; i++)
{
    for (int j = 1; j < N; j++)
    {
        matrix[i][j] = (i+1)*pow(r,j); 
        //note that you'll probably have to do some typecasting
        //p.s. I'm not 100% sure that this is the correct formula
    }
}

我認為這就是您想要的。 讓我知道它是否有效,因為我自己還沒有測試過。

像這樣打印矩陣:

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        std::cout << matrix[i][j] << " ";
    }
    std::cout << "\n";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM