0

我在 Microsoft Visual Studio 2010 中做了这个程序,就像另一个人做的一样,但是当它看到生成的产品矩阵时,矩阵的第一行是正确的,但矩阵下面的其他两行是错误的

所以它看到了这个错误的矩阵

5.3 23.9 24
-9.25596e+061 56.3 60.2
416 497.1 2980.9

我的程序应该看到的正确答案/矩阵是

5.3 23.9 24

11.6 56.3 58.2

17.9 88.7 92.4

因为我乘以这个矩阵1

1 2 3
4 5 6
7 8 9

通过这个矩阵2

0 2 4

1 4.5 2.2

1.1 4.3 5.2

这是代码

// 
//
// 
//
//Purpose: program that multiplys two matrices

#include <iomanip>
#include <iostream>

using namespace std;



const int N = 3;

void multiplyMatrix(const double a[][N], const double b[][N], double c[][N]);


int main()
{
    const double matrix1[][N] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};               //matrix 1
    const double matrix2[][N] = {{0, 2, 4},{1, 4.5, 2.2},{1.1, 4.3, 5.2}};     //matrix 2

    double matrix[][N]= {0};

      multiplyMatrix(matrix1, matrix2, matrix);






     return 0;
}


void multiplyMatrix(const double a[][N], const double b[][N], double c[][N])
{
    for ( int i = 0; i < 3 ; i++)
    {
        for ( int j = 0; j < 3; j++)
        {
            for ( int r = 0; r < 3; r++)
            {
                c[i][j] += (a[i][r] * b[r][j]);
            }
            cout << c[i][j] << setw(7);
        }
        cout << endl;
    }


}

请帮忙

4

1 回答 1

2

您实际上没有为结果分配任何内存。当您声明时,编译器无法理解您将结果设为 3x3 矩阵:

double matrix[][N]= {0};

与这种情况不同:

const double matrix1[][N] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}}; 

编译器将其“理解”为 3x3 矩阵。

更改double matrix[][N]= {0};double matrix[N][N]= {0};,您的问题将得到解决。

顺便说一句,你有一个分段错误/堆栈溢出,因为你只有 3 个双打的空间,但你使用了 9 个。

于 2013-11-01T08:30:40.117 回答