我創建了一個名為 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;
}
uj5u.com熱心網友回復:
我更改了您的索引邏輯,看起來還可以。仍然不明白你為什么使用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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434780.html
