无法在矩阵乘法中指定起始行和结束行

时间:2013-03-19 18:40:41

标签: c loops matrix-multiplication

我为矩阵乘法编写了一个c程序。现在我想将行数分成5个N / 5块。函数应该在第一次迭代中计算第一行块,在第二次迭代中计算第二部分,依此类推。如何在每次迭代中指定起始行和结束行?我在下面尝试过。任何人都可以帮我纠正它。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, m, n, p, q, c, d, k,g, sum = 0,start=0,end=m/5;
    int **first, **second, **multiply;
    printf("Enter the number of rows and columns of first matrix\n");
    scanf("%d%d", &m, &n);
    printf("Value entered %d%d \n",m,n);
    first = malloc(m*sizeof(int*));
    for ( i =0;i <m; i++)
        first[i] =malloc(n*sizeof(int));
    printf("Enter the number of rows and columns of second matrix \n");
    scanf("%d%d", &p,&q);
    printf("value entered %d%d \n",p,q);
    second = malloc(p*sizeof(int*));
    for( i=0;i<p;i++)
        second[i] = malloc(q*sizeof(int));
    multiply = malloc(m*sizeof(int*));
    for ( i=0;i<m;i++)
        multiply[i] = malloc(q*sizeof(int));
    printf("Enter the elements of first matrix\n");
    for( c = 0 ; c < m ; c++ )
        for ( d = 0 ; d < n ; d++ )
            scanf("%d", &first[c][d]);
    if ( n != p )
        printf("Matrices with entered orders can't be multiplied with each other.\n");
    else {
        printf("Enter the elements of second matrix\n");
        for ( c = 0 ; c < p ; c++ ){
            for ( d = 0 ; d < q ; d++ )
                scanf("%d", &second[c][d]);
        }
        for(g=0;g<5;g++){
            for ( c = start ; c < end ; c++ ) {
                for ( d = 0 ; d < q ; d++ ) {
                    for ( k = 0 ; k < p ; k++ ) {
                        sum = sum + first[c][k]*second[k][d];
                    }
                    multiply[c][d] = sum;
                    sum = 0;
                }
            }
            start=start+m/5+1;
            end=end+m/5;
        }

        printf("Product of entered matrices:-\n");
        for ( c = 0 ; c < m ; c++ ) {
            for ( d = 0 ; d < q ; d++ )
                printf("%d\t", multiply[c][d]);
            printf("\n");
        }
        for ( i = 0; i < p; i++)
            free(second[i]);
        free(second);
        for ( i = 0; i < m; i++)
            free(multiply[i]);
        free(multiply);
    } 
    for ( i = 0; i < m; i++)
        free(first[i]);
    free(first);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

开始索引通常0(读取总是),但关于结束索引,

当您分配/构建矩阵时,您必须将它们保存在变量rows / cols中。