问题
so I am having an issue multiplying two 2d arrays together. I am pretty sure that matrixA and matrixB are being stored properly, they are displayed properly when the program is ran. When I try to multiply the 2 arrays together I am getting a long string of a lot of 1's and 0's. Any idea on what could be the problem?
Here is my code:
#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]);
}
}
}
}
Here is how the text file looks that the array A is being pulled from:
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
回答1:
Seems something wrong here:
matrixA[i][j] = *data;
You should use
matrixA[i][j] = *(data + i*5 + j);
Also, try printing:
printf("%d ",matrixC[i][n]);
inside second loop n
(after innermost loop j
).
来源:https://stackoverflow.com/questions/18840877/multiplying-two-2d-arrays