【发布时间】:2019-03-20 00:58:18
【问题描述】:
我有这个 C++ 类矩阵(参见下面的代码片段)。
在我的随机化方法中,我设置了 matr 的所有值(matr 是一个 2x2 矩阵)。
当我调用 print_matrix 时,它会复制元素 (1,0) 和 (1,1) 并将它们都打印两次,以及不打印 (0,0) 或 (0,1)。
我做错了什么?
查看下面的输出。
class Matrix {
public:
int rows;
int cols;
double rnd;
double* matr;
Matrix(int a, int b) {
printf(" vals %d %d \n", a, b);
rows = a;
cols = b;
matr = new double[a, b];
//this->print_matrix();
//clear_matrix();
//this->print_matrix();
//this->randomize();
//this->print_matrix();
}
double &at(int pos1, int pos2) {
return matr[pos1, pos2];
};
void setPos(int pos1, int pos2, double value) {
matr[pos1, pos2] = value;
};
void randomize() {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
rnd = double(rand()) / double((RAND_MAX)+1.0);
printf("Rand : %d, C: %d, Val: %f \n",r,c, rnd);
this->setPos(r, c, rnd);
//matr[r, c] = rnd;
printf("New value R: %d C: %d Val: %f \n", r, c, matr[r,c]);
//rnd = 0;
}
}
};
void subtract_Scalar(double val) {
double curr_Val = 0;
double result = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
curr_Val = this->at(r, c);
result = curr_Val - val;
this->setPos(r, c, 0);
this->setPos(r, c, (float)result);
//this->setPos(r, c, 5);
//printf("SS CV : %f, Re: %f \n", curr_Val, result);
curr_Val = 0;
result = 0;
}
}
};
void print_matrix() {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf("PM R : %d, C: %d Val: %f \n", r, c, matr[r,c]);
//printf("%f", this->at(r, c));
}
//printf("\n");
}
}
void clear_matrix() {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
this->setPos(r, c, 0.0);
}
}
}
};
【问题讨论】:
-
您在
matr = new double[a, b]中使用的语法与您在 C++ 中声明或访问二维数组的方式不同。听起来你可以使用good C++ book -
这还能编译吗?
-
@Ayxan 逗号操作符可以隐藏很多错误
-
@Ayxan 它确实可以编译。这也是我的第一个 C++ 程序...
-
@MattWard 从那里找到一个好的可靠的来源学习。 C++ 不是一种你应该尝试“随便学习”的语言