所以我在将两个二维数组相乘时遇到问题。我很确定 matrixA 和 matrixB 被正确存储,它们在程序运行时正确显示。当我尝试将 2 个数组相乘时,我得到一个包含很多 1 和 0 的长字符串。关于可能是什么问题的任何想法?
这是我的代码:
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
#include <iostream>
/* Routines called. */
int loadMatrixFromFile(char *filename, int *data);
void showMatrix(int *data, int len);
int makeIdent(int matrixB[5][5], int length);
int matrixA[5][5];
int matrixB[5][5];
int matrixC[5][5];
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]);
int main(){
int len, data[1000];
len = loadMatrixFromFile("Numbers.txt", data);
showMatrix(data, len);
makeIdent(matrixB,len);
multiplyMatrices(matrixA, matrixB, matrixC);
}
int makeIdent(int matrixB[5][5], int len)
{
int i,j;
printf("Matrix B = \n");
for(i=0;i<5;i++){
for(j=0;j<5;j++){
if(i==j){
matrixB[i][j]=1;
printf("%d ",matrixB[i][j]);
}
else{
matrixB[i][j]=0;
printf("%d ",matrixB[i][j]);
}
}
printf("\n");
}
return matrixB[i][j];
printf("\n");
}
int loadMatrixFromFile(char *filename, int *data)
{
FILE *in;
int len;
int j;
in = fopen(filename, "r");
if (in == NULL) {
printf("Could not find file: %s \n", filename);
}
else {
printf("Reading numbers...\n");
fscanf(in, "%d", &len);
printf("reading %d numbers from file %s ....\n", len, filename);
for(j=0;j<len;j++) {
fscanf(in, "%d", data + j);
}
fclose(in);
}
for(int i = 0; i<5; i++){
for(int j = 0; j < 5; j++){
matrixA[i][j] = *data;
}
}
return len;
}
void showMatrix(int *data, int len)
{
int j;
int count = 0;
printf("Showing %d numbers from data array....\n", len);
printf("Matrix A = \n");
for(j=0;j<len;j++) {
printf("%d ", *(data + j));
count++;
if(count % 5 == 0){
printf("\n");
}
}
printf("\n");
}
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]){
int i, n, j;
printf("\n");
printf("Matrix A x Matrix B = \n");
for (i = 0; i<5; i++){
for (n = 0; n<5; n++){
for (j = 0; j<5; j++){
matrixC[i][n] += matrixA[i][j]*matrixB[j][n];
printf("%d ",matrixC[i][n]);
}
}
}
}
以下是从文本文件中提取数组 A 的样子:
25
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7