首页 > 解决方案 > 将矩阵的一行乘以给定的数字

问题描述

我应该将给定矩阵的某一行(我在函数的第四个参数中指定哪一行)乘以一个数字。

主要功能:

int main_tp05(int argc, const char *argv[]){
    int mNx100[][MAXCOLS100] = {{1,2,3},{4,5,6},{7,8,9}};
    multiply_matrixNx100_line_by_scalar(mNx100,3,3,1,2);
    return  0;
}

我试图像这样解决它:

void multiply_matrixNx100_line_by_scalar(int mNx100[][MAXCOLS100], int lines, int columns, int line, int scalar){
    for (int i = 0; i < lines; i++) {
        for (int j = 0; j < columns; j++) {
            if(i == line){
                printf("%d\n", mNx100[i*scalar][j] );
            }
        }
        printf("\n");
    }
}

需要注意的是:

1- I can´t change the parameters.
2- MAXCOLS100 is a macro on the .h file. I put it with the value of 3.
3- The scalar is the number I want to multiply the line by. 

标签: cmatrix

解决方案


我应该将给定矩阵的某一行(我在函数的第四个参数中指定哪一行)乘以一个数字

通常,“将矩阵的一行乘以标量”是指将行的每个元素乘以某个标量值。这不是发布函数所做的,它将行的索引乘以传递的参数:

void multiply_matrixNx100_line_by_scalar(int mNx100[][MAXCOLS100], int lines, int columns,
                                         int line, int scalar) {
    for (int i = 0; i < lines; i++) {        // <-- Useless, the row is known
        for (int j = 0; j < columns; j++) {
            if(i == line){
                printf("%d\n", mNx100[i*scalar][j] );
                //                    ^^^^^^^^
            }
        }
        printf("\n");
    }
}

如果意图只打印修改后的行,则可以将前面的函数重写为

void multiply_matrixNx100_line_by_scalar(int mNx100[][MAXCOLS100], int lines, int columns,
                                         int line, int scalar) {
    if (line < 0  ||  line >= lines)
        return;
    for (int j = 0; j < columns; j++) {
        printf("%d\n", mNx100[line][j] * scalar);
    }
    printf("\n");
}

如果相反,该函数应该只修改矩阵而不打印它,我们可以使用

mNx100[line][j] *= scalar;

在循环内部,代替对printf.


推荐阅读