简体   繁体   中英

Why does my C program that is supposed to output a matrix to the power of n output my matrix to the power of 2^n?

My code is supposed to take in a matrix M and raise it to the power of an integer A. However, somehow, my output is always M^(2^A). For example, if I want to find a matrix in its 3rd power, I will instead receive its 8th power.

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h>
  void multiply(int ** p, int pwr, int dim, int ** prod) {
    int m, i, j, k;
    /*if (n<pwr){*/
    int pos = 0;
    for (m = 0; m < pwr; m++) {
      for (i = 0; i < dim; i++) {
        for (j = 0; j < dim; j++) {
          for (k = 0; k < dim; k++) {
            pos += p[i][k] * p[k][j];
          }
          prod[i][j] = pos;
          pos = 0;
        }
      }
      for (i = 0; i < dim; i++) {
        for (j = 0; j < dim; j++) {
          p[i][j] = prod[i][j];
          prod[i][j] = 0;
        }
      }
    }
    /*n=n+1;
    multiply(prod, q, pwr, dim, prod);
    }*/
  }
int main(int argc, char * argv[]) {
  FILE * fp = fopen(argv[1], "r");
  int dim, pwr, i, j;
  fscanf(fp, "%d", & dim);
  int ** matrix;
  matrix = (int ** ) malloc(dim * sizeof(int * ));
  for (i = 0; i < dim; i++) {
    matrix[i] = (int * ) malloc(dim * sizeof(int));
  }
  int ** prod;
  prod = (int ** ) malloc(dim * sizeof(int * ));
  for (i = 0; i < dim; i++) {
    prod[i] = (int * ) malloc(dim * sizeof(int));
  }
  for (i = 0; i < dim; i++) {
    for (j = 0; j < dim; j++) {
      fscanf(fp, "%d", & matrix[i][j]);
    }
  }
  fscanf(fp, "%d", & pwr);
  if (pwr == 1) {
    for (i = 0; i < dim; i++) {
      for (j = 0; j < dim; j++) {
        printf("%d ", matrix[i][j]);
      }
      printf("\n");
    }
  } else if (pwr >= 2) {
    multiply(matrix, pwr, dim, prod);
    for (i = 0; i < dim; i++) {
      for (j = 0; j < dim; j++) {
        printf("%d ", matrix[i][j]);
      }
      printf("\n");
    }
  }
  return 0;
}

You are multiplying your matrix by itself and then store the result in the original one. Then you do it again.

So perfectly normal that it gets powered 8 times. What you need is another temporary matrix on which you store the result and keep the original matrix to multiply your result with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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