首页 > 解决方案 > 如何使用指针将用户输入矩阵提高到 n 次方,现在我只能计算到 2 的幂

问题描述

我试图将用户输入的 MXM 矩阵提高 n 次方,但我只能将矩阵提高到 2 的幂。如果我输入任何其他高于 2 的数字,它只会使矩阵提高到 2 的幂。我如何使用指针来做到这一点?


int main() {
    int M = 0;
    int N = 0;
    printf("Enter the size of R: ");
    scanf("%d",&M);
    printf("Enter the value of power N: ");
    scanf("%d",&N);
    int R[M][M]; //maximum dimension = 5
    int result[M][M];
    int newR[M][M];
    if (M < 1 || M > 5)
    {
        printf("Error: Size of M must stay between 1 to 5.\n");
    }
    else
    {
        for (int i = 0; i < M; i++){
               for (int j = 0; j < M; j++){
                   printf("Enter data in R(%d,%d): ",i+1,j+1);
                   scanf("%d",&R[i][j]);
               }
           }
           for (int i  = 0; i < M; i++){
               for (int j = 0; j < M; j++){
               printf("R(%d,%d) = %d\n",i+1,j+1,newR[i][j]);
               }
           }
    }
    int sum = 0;
    for (int i = 0; i < N; i++)
    {
        for ( int row = 0 ; row < M ; row++ )
        {
            for (int col = 0 ; col < M ; col++ )
            {
                for (int count = 0 ; count < M ; count++ )
                {
                    sum += R[row][count]*R[count][col];
                }
                result[row][col] = sum;
                printf("%d\n",result[row][col]);
                sum = 0;
            }
         }
        for (int row = 0; row < M; row++)
        {
            for (int col = 0 ; col < M ; col++ )
            {
                newR[row][col] = result[row][col];
//                R[row][col] = 0;
            }
        }
    }
    for (int i  = 0; i < M; i++){
        for (int j = 0; j < M; j++){
        printf("newR(%d,%d) = %d\n",i+1,j+1,newR[i][j]);
        }
    }
    return 0;
}```

标签: c++pointersmatrixmatrix-multiplication

解决方案


推荐阅读