2013-12-16 27 views
0

我自己學習C++,解決不同的問題。 我想解決最初爲C++中的Pascal設計的問題。 它應該要求用戶輸入3個整數M,N和q。 然後,它應該製作2d的整數大小爲MxN的數組,其中(I = I,... M)行的所有元素將成爲幾何級數的成員,第一個元素等於行數(I),分母q 。C++用戶自定義2維陣列,幾何級數

我想創建一個動態的大規模,但我意識到它不會真的與兩個未定義的整數工作。所以,我嘗試了矢量。我想我是以正確的方式創建它們的,但我不知道如何製作幾何圖形。

這裏是我的代碼:

#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; 





} 

回答

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等。我不確定你的意思是「行」,因爲你沒有在你的代碼中引用任何這樣的變量。

編輯

所以一旦創建了m×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(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"; 
} 
+0

感謝您的回覆!我想這條線是矩陣的行,例如它應該看起來像這樣。如果它是3x3矩陣。 {1 3 6} {2 6 12} {3 12 24}我就是這麼想的。 –

+0

因此,例如,矩陣[0] [0]將從0開始,矩陣[1] [0]將從一開始? –

+0

是的,行中的第一個數字表示行號。那麼從第二個數字開始的每個數字都是從前面的數字次數q開始的。所以它就像[1 1q 1q * q] –