#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void matrixRandomFill(int size, int size2, int matrix[size][size2]) {
srand(time(NULL));
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrix[i][j] = rand() % 9;
}
}
}
void matrixSum(int size, int size2, int matrix1[size][size2], int matrix2[size] [size2], int matrixSum[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrixSum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}
void matrixSubstract(int size, int size2, int matrix1[size][size2], int matrix2[size] [size2], int matrixSubstract[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrixSubstract[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
void matrixMultiply(int size, int size2, int matrix1[size][size2], int matrix2[size] [size2], int matrixMultiply[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrixMultiply[i][j] = matrix1[i][j] * matrix2[i][j];
}
}
}
void matrixPrint(int size, int size2, int matrix[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int size;
printf("Enter matrix size NxN: ");
scanf("%d", &size);
int matrix1[size][size];
int matrix2[size][size];
int matrixSum[size][size];
int matrixSubstract[size][size];
int matrixMultiply[size][size];
matrixRandomFill(size, size, matrix1);
matrixRandomFill(size, size, matrix2);
printf("Printing first matrix:\n");
matrixPrint(size, size, matrix1);
printf("--------------------------------------\n");
printf("Printing second matrix:\n");
matrixPrint(size, size, matrix2);
printf("--------------------------------------\n");
printf("Printing matrix1 + matrix2:\n");
matrixPrint(size, size, matrixSum);
printf("--------------------------------------\n");
printf("Printing matrix1 - matrix2:\n");
matrixPrint(size, size, matrixSubstract);
printf("--------------------------------------\n");
printf("Printing matrix1 * matrix2:\n");
matrixPrint(size, size, matrixMultiply);
printf("--------------------------------------\n");
return 0;
}
函数看起来很正常,但我不断得到这样的东西: 打印矩阵1 +矩阵2: 0 0 0 0 0 0 0 0 0
或
打印矩阵1 - 矩阵2: -1761243347 32767 -1761341440 32767 0 0 0 0 0
看起来像某种分段错误,但我无法弄清楚我犯了哪个错误。
答案 0 :(得分:2)
问题是你只是打印矩阵而不是在它之前执行任何操作。
// You forgot to call matrix sum function here.
printf("Printing matrix1 + matrix2:\n");
matrixPrint(size, size, matrixSum);
printf("--------------------------------------\n");
类似于减法,乘法运算。
答案 1 :(得分:1)
你的函数matrixSum等永远不会被调用。
答案 2 :(得分:1)
正如其他人所说,你从来没有真正评估过matrixSum和其他的,我发现你的本地(对主要)变量与你的函数同名隐藏了你的函数,所以它们将不再可用于那些变量声明
我看到你的另一个问题的方式是(例如):
int iwilldosomething(int a, int b) /*function iwilldosomething */
int main(void)
{
int iwilldosomething; /* local variable iwilldosomething */
iwilldosomething(2, 3); /* here you will get error, because main can see iwilldosomething and will tell that iwilldosomething is not a function */
.
.
.