繁体   English   中英

我将如何确保这两个矩阵的行和列值为非零?

[英]How would I go about making sure these two matrices have non-zero, positive row and column values?

我设置代码时没有考虑需要检测到这一事实,结果,我似乎无法弄清楚现在如何实现它。 这是一个简单的矩阵乘法器。

基本上,它需要检测两个条件。

  1. 如果矩阵1中的列不等于矩阵2中的行,则退出程序并显示错误消息。 我已经做到了

  2. 如果用户为矩阵1和矩阵2输入的行和列值是非零正值。 我有这个问题。

教授设置的方式是,我们复制并粘贴一组值并执行该操作。 但是,如果我们将其复制并粘贴到输入中,那么我将感到困惑,当为了接受我正在使用的for循环扫描其中所有值的其余数据时,行和列应该如何检测错误? ,并且for循环的长度取决于matrix1和matrix2的行和列的输入。 如果这些为负,则for循环将无法正常工作。

真的,任何帮助将不胜感激,除了这一分钟的细节,我已经完成了所有其他部分。 非常感谢。

#include <stdio.h>

int main(int argc, char *argv[]) {
    int rows1 = 1, columns1 = 1, rows2 = 1, columns2 = 1;    // variables for number of rows and columns in each matrix 
    int i, j, k;                                             // loop variables 

    // These will affect the loop's length
    scanf("%d %d", &rows1, &columns1);
    int matrix1[rows1][columns1];
    for (i = 0; i < rows1; i++) {
        for (j = 0; j < columns1; j++) {
            scanf("%d", &matrix1[i][j]);
        }
    }

    scanf("%d %d", &rows2, &columns2);
    int matrix2[rows2][columns2];
    for (i = 0; i < rows2; i++) {
        for (j = 0; j < columns2; j++) {
            scanf("%d", &matrix2[i][j]);
        }
    }

    int resultMatrix[rows1][columns2]; // Initialization of resultMatrix, that holds the result of the multiplication

    int matrix1RowIndex = 0, matrix1ColIndex = 0, matrix2ColIndex = 0;

    if (columns1 != rows2) {
        printf("Sorry, the amount of columns in the first matrix must equal the amount of rows in the second matrix.\n");
    }
    else {      
        // Loop to set the values of resultMatrix's indices
        for (i = 0; i < rows1; i++) { // rows
            for (j = 0; j < columns2; j++) { // columns
                resultMatrix[i][j] = 0;
                for (k = 0; k < columns1; k++) { // for each individual index to be summed for the resultMatrix's value
                    resultMatrix[i][j] += (matrix1[matrix1RowIndex][matrix1ColIndex + k] * matrix2[matrix1ColIndex + k][matrix2ColIndex]);
                }
                matrix2ColIndex++;
            }
            matrix1RowIndex++;
            matrix2ColIndex = 0;
        }

        //prints resultMatrix
        for (i = 0; i < rows1; i++) { // rows
            for (j = 0; j < columns2; j++) { // columns
                printf("%6d", resultMatrix[i][j]);
            }
            printf("\n");
        }
    }
}

看来您可以使用if语句检查所讨论的值是否大于零,不是吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM