2013-10-12 60 views
-3

我只是C++的初學者,我想編寫一個程序,輸入並顯示一個訂單i * j的矩陣。我寫了下面的程序,但沒有奏效。在C++中輸入一個矩陣?

請親引導我。

我認爲可能是訪問的方法是不對的或類似的東西。

下面是程序:

#include <iostream> 

using namespace std; 

int main() { 
    int i = 0,j = 0; 

    cout << "Enter no of rows of the matrix"; 
    cin >> i; 
    cout << "Enter no of columns of the matrix"; 
    cin >> j; 

    float l[i][j]; 

    int p = 0, q = 0; 

    while (p < i) { 
    while (q < j) { 
     cout << "Enter the" << p + 1 << "*" << q + 1 << "entry"; 
     cin >> l[p][q]; 

     q = q + 1; 
    } 
    p = p + 1; 
    q = 0; 
    } 
    cout << l; 
} 
+0

請解釋究竟是什麼不起作用。如果您收到任何意外的輸出或錯誤信息,請將它們複製並粘貼到您的問題中。 –

+0

我沒有得到所需的輸出 – user2874452

+0

我想輸入後打印矩陣。 – user2874452

回答

1

你不能限定具有可變長度的數組。您需要定義一個動態數組或std :: vector的

#include<vector> 
std::vector<std::vector<int> > l(i, std::vector<int>(j, 0)); 

而且cout << l將只打印出int**的價值。要打印出每個單獨的整數,您需要針對每個整數進行循環。

for(int x = 0; x < i; ++i){ 
    for(int y = 0; y < j; ++y){ 
    cout << l[x][y] << " " 
    } 
    cout << "\n"; 
} 
+1

請不要這樣做。使用'std :: vector'。 –

+1

@ n.m。好的,C++的問題有一個C++的答案。 –

+0

我沒有說不使用'std :: vector'。如果可以,請始終使用它。 –

1

我重寫代碼: (而不是ALLOC它能夠更好地使用C++新的,並用delete釋放內存)

#include "stdafx.h" 
#include<iostream> 
#include <conio.h> 
    using namespace std; 
int _tmain() 
{ 
    int row,col; 

cout<<"Enter no of rows of the matrix"; 
cin>>row; 
cout<<"Enter no of columns of the matrix"; 
cin>>col; 

float** matrix = new float*[row]; 
for(int i = 0; i < row; ++i) 
    matrix[i] = new float[col]; 
int p=0,q=0; 

for(unsigned i=0;i<row;i++) { 
    for(unsigned j=0;j<col;j++) { 
     cout<<"Enter the"<<i+1<<"*"<<j+1<<"entry"; 
     cin>>matrix[i][j]; 
    } 
} 

for(unsigned i=0;i<row;i++) { 
    for(unsigned j=0;j<col;j++) { 
     cout<<matrix[i][j]<<"\t"; 
    } 
    cout<<endl; 
} 

    getch(); 
    return 0; 
} 
+0

好的。非常感謝。 – user2874452