【问题标题】:Multiplication of a 3x3 matrix and a 3x1 vector3x3 矩阵和 3x1 向量的乘法
【发布时间】:2017-10-13 18:30:21
【问题描述】:

我的程序要求用户输入一个 3 维双向量 v 和一个 3 x 3 双矩阵 M,程序将打印出矩阵/向量乘积 Mv。但是我没有得到一个向量作为我的输出,我得到了一个标量。我不知道为什么,我已经将我的输出定义为一个向量。这是代码

#include <iostream>

using namespace std;

int main()

{
    double v[3][1];
    double M[3][3];
    double Mv[3][1];
    int i,j;

    cout << "Enter in the components of the vector v:\n";

for(i=0; i<3; i++)
{
    cout << "Component " << i+1 << ": ";
    cin >> v[i][0];
}

    cout << "Enter in the components of the 3 x 3 matrix M:\n";

for(i=0; i<3; i++)
{
    for(j=0; j<3; j++)
    {
        cin >> M[i][j];
    }
}   

for(i=0; i<3; i++)
{
    Mv[i][0]= 0.0;
    for(j=0; j<3; j++)
    {
        Mv[i][0] += (M[i][j] * v[j][0]);
    }
}
cout << "The product of Mv is: " << Mv[i][0] << endl;   
return 0;
}

代码将产品打印为“1” - 如果我为两个向量的所有元素输入 1。

【问题讨论】:

  • 你打印Mv[4][0]是UB,你想打印Mv[0][0]Mv[1][0]Mv[3][0]
  • cout &lt;&lt; "The product of Mv is: " &lt;&lt; Mv[i][0] &lt;&lt; endl; 在循环之外,所以你得到的只是Mv[3][0]。将行移到右大括号之前,它应该可以按预期工作
  • [OT]:double v[3][1] 有什么意义,而您可以使用double v[3](并摆脱[0])?

标签: c++ arrays calculator


【解决方案1】:

cout放在上面一行:

for(i=0; i<3; i++)
{
    Mv[i][0]= 0.0;
    for(j=0; j<3; j++)
    {
        Mv[i][0] += (M[i][j] * v[j][0]);
    }
    cout << "The product of Mv is: " << Mv[i][0] << endl;
}

【讨论】:

  • 那将打印行 Mv 的乘积是 3 倍 ;)
  • 好吧,printf("Mv[%d][0] = %.3f\n", i, Mv[i][0]); 会更好看。 :)
【解决方案2】:

您只在输出调用中打印一个值 Mv[i][0]

您需要创建一个循环来打印所有矢量元素:

代替:

cout << "The product of Mv is: " << Mv[i][0] << endl;

做:

cout << "The product of Mv is: [";

// start with the delimiter as a ',' but we need to change it 
// to ']' on the last iteration of the loop.
// so the result looks something like "[1.4,2.5,0.2]"
char delimiter = ',';

for(i=0; i<3; i++)
{
   if (i == 2)
   {
      // on last loop iteration change delimiter to ']'
      delimiter = ']'
   }

   cout << Mv[i][0] << delimiter;
}

cout << endl; 

【讨论】:

  • 您可以按照 Olia 的建议将此循环与您的计算循环合并。
  • 哦,谢谢,我做到了。我知道我不能将“矩阵的乘积”放在同一个循环中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 2020-03-16
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多