如何使用c中的指针计算矩阵的行列式?
How to calculate determinant of a matrix using pointers in c?
我正在编写一个程序来使用大小最大为 3x3 的指针计算矩阵的行列式,并且我已经开始编写 2x2 矩阵的公式。
我收到一个错误,它在相乘表达式开头的括号位置显示 "expression must have arithmetic type"。
程序似乎将值识别为指针,而不仅仅是将值相乘,但我也不确定。我该如何解决?
void determinant(int size, int matrix[][MAXSIZE])
{
int d;
if(size == 2)
{
d = matrix * ((matrix + 1) + 1) - ((matrix + 1) + 0) * ((matrix + 0) + 1);
printf("Determinant of your matrix: %d\n", d);
}
}
为什么不只是 matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]
?
不过,您可能应该向函数传递一个比 int matrix[][]
类型更安全的参数(例如,创建某种类型的 struct MATRIX_2_2
)。
为了练习,如果你真的想使用指针运算,你可能想写这样的东西:
d = (**matrix) * (*(*(matrix + 1) + 1)) - (*(*(matrix + 0) + 1)) * (*(*(matrix + 1) + 0));
在这里,每个第一个 de-reference(这就是星号)获得矩阵的一维数组,第二个获得特定值。
计算 determinant 的问题是一个基础数学问题(与 C 完全无关),大多数线性代数课程都会解释如何计算。您实际上需要了解如何计算 "by hand".
一个不同的问题是如何表示矩阵(作为abstract data type) in a C program. I would suggest using flexible array members (and pointers to struct
-s containing them), and I detailed more how to do that in 答案(当然你需要完成你的需要)。
通过结合两种方法(数学方面和编程方面),您可以完成作业。
编译时不要忘记启用所有警告和调试信息(例如使用 gcc -Wall -Wextra -g
和 GCC; see also the advice given ), and read How to debug small programs 进行编译。
我正在编写一个程序来使用大小最大为 3x3 的指针计算矩阵的行列式,并且我已经开始编写 2x2 矩阵的公式。
我收到一个错误,它在相乘表达式开头的括号位置显示 "expression must have arithmetic type"。
程序似乎将值识别为指针,而不仅仅是将值相乘,但我也不确定。我该如何解决?
void determinant(int size, int matrix[][MAXSIZE])
{
int d;
if(size == 2)
{
d = matrix * ((matrix + 1) + 1) - ((matrix + 1) + 0) * ((matrix + 0) + 1);
printf("Determinant of your matrix: %d\n", d);
}
}
为什么不只是 matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]
?
不过,您可能应该向函数传递一个比 int matrix[][]
类型更安全的参数(例如,创建某种类型的 struct MATRIX_2_2
)。
为了练习,如果你真的想使用指针运算,你可能想写这样的东西:
d = (**matrix) * (*(*(matrix + 1) + 1)) - (*(*(matrix + 0) + 1)) * (*(*(matrix + 1) + 0));
在这里,每个第一个 de-reference(这就是星号)获得矩阵的一维数组,第二个获得特定值。
计算 determinant 的问题是一个基础数学问题(与 C 完全无关),大多数线性代数课程都会解释如何计算。您实际上需要了解如何计算 "by hand".
一个不同的问题是如何表示矩阵(作为abstract data type) in a C program. I would suggest using flexible array members (and pointers to struct
-s containing them), and I detailed more how to do that in
通过结合两种方法(数学方面和编程方面),您可以完成作业。
编译时不要忘记启用所有警告和调试信息(例如使用 gcc -Wall -Wextra -g
和 GCC; see also the advice given