3x3矩阵和3x1向量的乘法

时间:2017-10-13 18:30:21

标签: c++ arrays calculator

我的程序要求用户输入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。

2 个答案:

答案 0 :(得分:0)

您只在输出调用中打印一个值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; 

答案 1 :(得分:0)

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