在 C++ 中输入一个矩阵?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19336869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:44:22  来源:igfitidea点击:

Input a matrix in c++?

c++matrix

提问by user2874452

I'm just a beginner of C++and I want to write a program which inputs and then displays a matrix of order i * j. I have written the following program but it did not work.

我只是一个初学者,C++我想编写一个程序,输入然后显示顺序矩阵i * j。我编写了以下程序,但它不起作用。

Kindly guide me .

请指导我。

I think may be the method of accessing is not right or something like that.

我想可能是访问方法不对或类似的东西。

Here is the program:

这是程序:

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

回答by Zac Wrangler

you cant define an array with variable length. You need to define a dynamic arrays or std::vector

你不能定义一个可变长度的数组。您需要定义一个动态数组或 std::vector

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

And cout << lwill only print out the value of a int**. To print out each individual integer, you need to loop against each of them.

并且cout << l只会打印出 a 的值int**。要打印出每个单独的整数,您需要对每个整数进行循环。

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

回答by AndyBaba

I rewrote your code: (instead of alloc its better to use new in c++, and use delete to free the memory)

我重写了你的代码:(在c++中使用new而不是alloc更好,并使用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;
}