alimohsen
Grünschnabel
Hallo leute,
ich habe ein programm geschrieben dass 2 3 mal 3 matrizen aus einer datei (matrix.txt) ausliest, sie miteinander multipliziert und in eine andere datei abspeichert. ich sollte jedoch kein malloc benutzen, und die programmteile in fuktionen einteilen (einlesen, multiplizieren, ausgeben, abspeichern)
hilft mir bitte !!!
ich habe ein programm geschrieben dass 2 3 mal 3 matrizen aus einer datei (matrix.txt) ausliest, sie miteinander multipliziert und in eine andere datei abspeichert. ich sollte jedoch kein malloc benutzen, und die programmteile in fuktionen einteilen (einlesen, multiplizieren, ausgeben, abspeichern)
hilft mir bitte !!!
C:
#include <stdio.h>
#include <stdlib.h>
#define n 3
int main()
{
int i;
int j;
// Allocate enough memory for the arrays and the result
int** mat=malloc(n*sizeof(int*));
int** mat2=malloc(n*sizeof(int*));
int** result=malloc(n*sizeof(int*));
for(i=0;i<n;++i){
mat[i]=malloc((2*n)*sizeof(int));
mat2[i]=malloc((2*n)*sizeof(int));
result[i]=malloc((2*n)*sizeof(int));
}
// Open the file to read
FILE *file;
file=fopen("matrix.txt", "r");
//Copy the matrices to the arrays mat and mat2
for(i = 0; i < 2*n; i++)
{
for(j = 0; j < n; j++)
{
//When i reaches n we should set it to 0 to enable writing to the second array mat2
if(i > n-1){
if (!fscanf(file, "%i", &mat2[i-n][j]))
break;
printf("%i ",mat2[i-n][j]);
}else{
//Use lf format specifier, %c is for character
if (!fscanf(file, "%i", &mat[i][j]))
break;
printf("%i ",mat[i][j]); //Use lf format specifier, \n is for new line
}
}printf("\n");
}
// Matrices product
int k;
int sum;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
sum = 0;
for (k = 0; k < n; k++) {
sum = sum + mat[i][k] * mat2[k][j];
}
result[i][j] = sum;
}
}
//Print the result as matrix format
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf(" %i ", result[i][j]);
}
printf("\n");
}
// Close the file after all tasks are fixed
fclose(file);
return (0);
}
Zuletzt bearbeitet von einem Moderator: