如何使用断言对数组进行测试

How to make a test with arrays using asserts?

本文关键字:测试 数组 何使用 断言      更新时间:2023-10-16

我正在尝试为程序编写一个测试,该程序将矩阵AX的乘积添加到矩阵Y中。但是我有错误:

"Identifier is required"

我无法解决或找到解决此问题的解决方案,所以我在这里寻求帮助。

起初,我认为问题是我将其与错误的数组进行了比较。然后我尝试通过其他参数。将我的代码分解为多个功能。但是,什么都没发生。

#include<iostream>
#include<cassert>
using namespace std;
void axpy(int n, int m, int k, int **A, int **X, int **Y)
{
    int i, j, q;
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < m; j++)
        {
            for (q = 0; q < k; q++)
            {
                Y[i][j] += A[i][q] * X[q][j];
            }
        }
    }
    cout << "Product of matricesn";
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < m; j++)
            cout << Y[i][j] << "  ";
        cout << "n";
    }
}
void TestAxpy()
{
    int P[2][2] = { {13,11},{27,21} };
    assert(axpy(2,2,2,[1,2][3,4],[4,3][2,1],[5,6][7,8]) == P);
}
int main()
{
    int n, m, k, i, j, q;
    cout << "Enter number of rows of matrix X and columns of matrix A: ";
    cin >> k;
    cout << "Enter number of rows of matrix A and Y: ";
    cin >> n;
    cout << "Enter number of columns of matrix X and Y: ";
    cin >> m;
    int **A = new int *[k];
    for (i = 0; i < k; i++)
        A[i] = new int[n];
    int **X = new int *[m];
    for (i = 0; i < m; i++)
        X[i] = new int[k];
    int **Y = new int *[m];
    for (i = 0; i < m; i++)
        Y[i] = new int[n];

    cout << "Enter elements of matrix A: ";
    for (i = 0; i < n; i++)
        for (j = 0; j < k; j++)
            cin >> A[i][j];
    cout << "Enter elements of matrix X: ";
    for (i = 0; i < k; i++)
        for (j = 0; j < m; j++)
            cin >> X[i][j];
    cout << "Enter elements of matrix Y: ";
    for (i = 0; i < n; i++)
        for (j = 0; j < m; j++)
            cin >> Y[i][j];
    axpy(n, m, k, A, X, Y);
    TestAxpy();
    system("pause");
    return 0;
}

我想获得一个2x2矩阵,其中[13, 11] [27 21]的结果。我使用的输入,例如:

Enter number of rows of matrix X and columns of matrix A: 2
Enter number of rows of matrix A and Y: 2
Enter number of columns of matrix X and Y: 2
Enter elements of matrix A: 1 2 3 4
Enter elements of matrix X: 4 3 2 1
Enter elements of matrix Y: 5 6 7 8

这似乎是C和C 的混合。在C 中,很少需要使用RAW" C"数组,几乎总是std::vector<>std::array<>将是一个更好的选择。Boost库中也有矩阵,它将准确存储您需要的内容。

根据您的特定代码,有两个问题:

  1. 指向指针(**(的指针与二维数组不一样。它们是两层间接的。第一个是通往存储在内存中第二层的内存位置的指针。请参阅下文,以获取如何工作才能致电Axpy。再次强烈建议您查看std :: vector或Boost库。
  2. " =="操作员在C数组中无法使用这种方式。您需要指定如何进行比较。正如书面的那样,它充其量只会比较内存地址,但更有可能会产生错误。
void TestAxpy()
{
    int P[2][2] = { {13,11},{27,21} };
    int A1[2] = {1,2};
    int A2[2] = {3,4};
    int* A[2] = { A1, A2 };
    int X1[2] = {4,3};
    int X2[2] = {2,1};
    int *X[2] = { X1, X2 };
    int Y1[2];
    int Y2[2];
    int *Y[2] = {Y1, Y2 };    
    axpy(2,2,2,A,X,Y);
    //assert(Y == P); //C++ doesn't know how to do this.
}