0

我创建了一个名为 matrix 的类,它将值存储在一维数组中,但将其输出为二维数组。我已经包含了打印语句来显示应该放入数组中的确切值,但是当我使用打印函数对其进行索引时,它在第二行最后一个索引上显示不正确的值。不完全确定我做错了什么。

#include <iostream>

class Matrix
{
    private:
        int rows{}, cols{};
        double *newArr;
    public:
        Matrix(int row, int col)
        {
            rows = row;
            cols = col;
            newArr = new double[rows * cols];
        }
        void setValue(int row, int col, double value)
        {
            std::cout << value << std::endl;
            newArr[row * row + col] = value;                
        }
        double getValue(int row, int col)
        {
            return newArr[row * row + col];                 
        }
        int getRows()
        {
            return rows;
        }
        int getCols()
        {
            return cols;
        }
        void print()
        {
            for (int i{}; i < rows; ++i){
                for (int j{}; j < cols; ++j){
                    std::cout << newArr[i * i + j] << " ";
                }
                std::cout << std::endl;
            }
        }
        ~Matrix()
        {
            delete[] newArr;
        }
};

int main()
{
    Matrix x(3, 4);

    for (int i{}; i < x.getRows(); i++){
        for (int j{}; j < x.getCols(); j++){
            x.setValue(i, j, (j+i)/2.0);                     
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;

    x.print();

    return 0;
}
4

1 回答 1

2

我更改了您的索引逻辑,看起来还可以。仍然不明白你为什么使用row * row + col而不是row * cols + col.

动态分配矩阵的大小并将 2d 矩阵布局为 1d。然后你应该使用长度来填充数组,而不是(row index)^2.

现场演示

#include <iostream>

class Matrix
{
    private:
        int rows{}, cols{};
        double *newArr;
    public:
        Matrix(int row, int col)
        {
            rows = row;
            cols = col;
            newArr = new double[rows * cols];
        }
        void setValue(int row, int col, double value)
        {
            std::cout << value << std::endl;
            newArr[row * cols + col] = value;                
        }
        double getValue(int row, int col)
        {
            return newArr[row * cols + col];                 
        }
        int getRows()
        {
            return rows;
        }
        int getCols()
        {
            return cols;
        }
        void print()
        {
            for (int i{}; i < rows; ++i){
                for (int j{}; j < cols; ++j){
                    std::cout << newArr[i * cols + j] << " ";
                }
                std::cout << std::endl;
            }
        }
        ~Matrix()
        {
            delete[] newArr;
        }
};


int main()
{
    Matrix x(3, 4);

    for (int i{}; i < x.getRows(); i++){
        for (int j{}; j < x.getCols(); j++){
            x.setValue(i, j, (j+i)/2.0);                     
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;

    x.print();

    return 0;
}
于 2022-03-01T04:07:06.960 回答