c++ - 二维数组中的最后一个空格;矩阵

标签 c++ arrays matrix multidimensional-array

除了一项任务外,我的整个程序都在运行并完美运行。 在我的 for 循环中,当我尝试打印我的 product_matrix 数组时,我得到了一个额外的空间 (""),因为我在每次迭代后添加了一个空间。

我为循环的每一列和每一行尝试了一个 if else 参数,但我一直没有成功。在这部分停留了几个小时,我认为是时候向专家寻求帮助了。

Here is what it should look like and what program is doing instead

这是我的代码:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(){
  int first_matrix[10][10];
  int second_matrix[10][10];
  int product_matrix[10][10];
  int column = 0, row =0;
  int x = 0, y = 0, m = 0, n = 0;
  string temp;
  int value;

  // putting user input into my first_matrix array.
 cout << "Enter first matrix:" << endl;
 while(true){
    getline(cin, temp);
    if (temp.length() == 0){
     break;
    }
stringstream ss(temp);
column = 0;
while (ss >> value){
  first_matrix[row][column] = value;
  column++;
}
row++;
}
  // assigning length of cols and rows
  x = row;
  y = column;

  // putting user input into my second_matrix array.
  row = 0;
  cout << "Enter second matrix:" << endl;
  while(true){
    getline(cin, temp);
    if (temp.length() == 0){
      break;
    }
    stringstream ss(temp);
    column = 0;
    while (ss >> value){
      second_matrix[row][column] = value;
      column++;
    }
    row++;
  }
  m = row;
  n = column;

 // checking if first and second matrix arrays have compatible dimensions.
  if (y == m){
    // multiplying first and second matrix and putting it into the product_matrix
    for(row = 0; row < x; row++){
      for (column = 0; column < n; column++){
        product_matrix[row][column] = 0;
        for (int k = 0; k < m;  k++){
          product_matrix[row][column] += (first_matrix[row][k] * second_matrix[k][column]);
        }
      }
    }
    //printing product_array.
   cout << "The product is:" << endl;
   for (row = 0 ; row < x; row++){
      for (column = 0; column < n; column++){
        cout << product_matrix[row][column] << " ";
      }
      cout << endl;
    }
  }
  else
     cout << "The two matrices have incompatible dimensions." << endl;

  return 0;
}

最佳答案

我会根据打印循环中的索引在换行符和空格之间进行选择:

for (row = 0 ; row < x; row++){
    for (column = 0; column < n; column++){
        cout << product_matrix[row][column];
        cout << (column == n - 1) ? "\n" : " ";
    }
}

如果您在最后 (n - 1) 列,此代码将打印一个换行符,并为所有其他列打印一个空格。你不需要 cout << endl在外循环中使用此方法。

如果你不熟悉

(condition) ? statement1 : statement1;

过程,它是一个简化的 if-else。相当于

if (condition) {
    statement1;
} else {
    statement2;
}

关于c++ - 二维数组中的最后一个空格;矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779595/

相关文章:

c++ - std::sort 用于 C++ 中的二维 vector

c++ - MinGW 中 GetBuffer 和 ReleaseBuffer 的 CString 方法有哪些替代方法?

java - 在 java 中创建交替数组方法,你能告诉我哪里出错了吗?

java - 互质数矩阵

java - 如何根据正态(高斯)分布对网格(矩阵)的单元格进行采样?

c++ - 从 C/C++ 中的 ** 矩阵中提取行/列

c++ - libmpc-dyld : Library not loaded - Reason: image not found

c++ - 将模拟类添加到 STL 容器

java - CSVWriter不会将ArrayList转换为Array

c - 在另一个 .c 文件的函数中使用函数?