简体   繁体   English

递归 C,将两个矩阵相乘,无显示

[英]Recursion C, multiplying two matrix, nothings display

Im passing two matrix from main to function multiply, to multiply two matrix but i dont see any display can anyone guide me, im very new in recursion.我将两个矩阵从主传递到 function 相乘,以相乘两个矩阵,但我没有看到任何显示可以指导我,我在递归方面非常新。 (Note its 3 by 3 Matrix already declared) (注意它的 3 x 3 矩阵已经声明)

const r=3;
const c=3;
const row=3;
int multiply(int a[r][c],int b[r][c]);
int display(int arr[][row]);

int multiply(int a[r][c],int b[r][c]){
    static r=0,c=-1;
    static int mul[3][3];
    if(r>3){
        printf("R");
        display(mul);
    }
    if(c==3){
        printf("R");
        r++;
        c=0;
    }
    else{
        c++;
        mul[r][c]=a[r][c]*b[r][c];
        multiply(a,b);
    }
}
int display(int mul[][row]){
    int i,j;
    printf("Matrix After Multiplication: \n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<row;j++){
            printf("%d ",mul[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int m_1[3][3]={1,2,3,
                   1,2,3,
                   1,2,3,}, m_2[3][3]={1,2,3,
                             1,2,3,
                             1,2,3,};
    multiply(m_1,m_2);
}

I assume that the code does element wise multiplication of two matrices in a very very convoluted way.我假设代码以非常复杂的方式对两个矩阵进行元素乘法。 Among other horrors the problem is likely here:除其他恐怖外,问题可能在这里:

multiply(a[r][c],b[r][c]);

It should be:它应该是:

multiply(a,b);

Otherwise the actual values are passed as pointers to arrays.否则,实际值将作为指向 arrays 的指针传递。


EDIT编辑

there are two more issues:还有两个问题:

  • add return after display to break recursion在显示添加 return 以中断递归
  • move recursive call to multiply() outside of else branch to advance if either row or column is increased.如果行或列增加,则将递归调用移动到else分支之外的multiply()以前进。

The updated code is:更新后的代码是:

int multiply(int a[r][c],int b[r][c]){
    static r=0,c=-1;
    static int mul[3][3];
    printf("%d %d\n", r, c);
    if(r>3){
        display(mul);
        return;
    }
    if(c==3){
        r++;
        c=0;
    }
    else{
        c++;
        mul[r][c]=a[r][c]*b[r][c];
    }
    multiply(a,b);
}

I can saw at least 4 errors:我可以看到至少 4 个错误:

int multiply(int a[r][c],int b[r][c]){
    static r=0,c=-1;
    static int mul[3][3];
    if(r>3){
        display(mul);
        return; // missing return to stop execution
    }
    if(c==3){
        r++;
        c=-1; // you have to restart from -1 due to pre increment
    }
    //else should be removed to continue recursion at the end of each row
    {
        c++;
        mul[r][c]=a[r][c]*b[r][c];
        multiply(a,b);  // you need to pass matrix, not single elements...
    }
}

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

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