[英]How can I use the same user defined function for matrix in C?
I need to use the same user defined function in C, for adding and subtracting matrices in C. 我需要在C中使用相同的用户定义函数,以便在C中添加和减去矩阵。
This should be the code I need to declare 这应该是我需要声明的代码
void matrixAddSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums);
right now I'm declaring two functions 现在我要声明两个功能
void matrixAdd(int arrayone[10][10], int arraytwo[10][10], int rows, int colums);
void matrixSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums);
When I debug my code it does the work but I need to reduce the amount of code that I have type. 当我调试代码时,它可以工作,但是我需要减少输入的代码量。 Here's my code definition.
这是我的代码定义。
void matrixAdd(int arrayone[10][10], int arraytwo[10][10], int rows, int colums){
int i, j;
int sumM[10][10];
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
sumM[i][j] = arrayone[i][j] + arraytwo[i][j];
printf("\t%d", sumM[i][j]);
}
printf("\n");
}
}
void matrixSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums){
int i, j;
int sumM[10][10];
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
sumM[i][j] = arrayone[i][j] - arraytwo[i][j];
printf("\t%d", sumM[i][j]);
}
printf("\n");
}
}
UPDATE UPDATE
dasblinkenlight Here's what I end up doing with your suggestions: dasblinkenlight以下是我对您的建议的最终看法:
Declared in main function int add =1; 在主函数中声明int add = 1; int sub = -1;
int sub = -1;
//user defined functions declaration
void matrixAddSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums, int mul);
//user defined function definition
void matrixAddSub(int arrayone[10][10], int arraytwo[10][10], int rows, int colums, int mul){
int i, j;
int sumM[10][10];
int scaM[10][10];
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
scaM[i][j] = mul * arraytwo[i][j];
}
}
for (i = 0; i < rows; i++){
for (j = 0; j < colums; j++){
sumM[i][j] = arrayone[i][j] + scaM[i][j];
printf("\t%d", sumM[i][j]);
}
printf("\n");
}
}
Consider: 考虑:
-1
. -1
。 Use these two facts to unify addition and subtraction. 使用这两个事实来统一加法和减法。 Write the following function:
编写以下函数:
static void matrixAddOrSubtract(
int arrayone[10][10]
, int arraytwo[10][10]
, size_t rows
, size_t columns
, int mul); // Multiply arraytwo[i][j] by mul before adding to arrayone[i][j]
Now both of your functions could be re-written as single-line invocations of matrixAddOrSubtract
: 现在,您的两个函数都可以重写为
matrixAddOrSubtract
的单行调用:
void matrixAdd(int arrayone[10][10], int arraytwo[10][10], size_t rows, size_t columns) {
matrixAddOrSubtract(arrayone, arraytwo, rows, columns, 1);
}
void matrixSub(int arrayone[10][10], int arraytwo[10][10], size_t rows, size_t columns) {
matrixAddOrSubtract(arrayone, arraytwo, rows, columns, -1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.