计算 2x2 矩阵的行列式

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在线性代数中,方阵的行列式(determinant)是一个可以从矩阵元素中计算出的标量值。在本实验中,我们将学习如何使用 C 语言编程计算 2x2 矩阵的行列式。

注意:你需要自己创建文件 ~/project/main.c 来练习编码,并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} c/operators -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} c/for_loop -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} c/arrays -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} c/math_functions -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} c/user_input -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} c/output -.-> lab-197928{{"`计算 2x2 矩阵的行列式`"}} end

理解概念

在开始之前,我们先来理解行列式的概念。一个 2x2 矩阵是一个包含 2 行和 2 列的数组,其行列式可以通过以下公式计算:

determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1]

其中,a[0][0]a[0][1]a[1][0]a[1][1] 是矩阵的元素。

初始化变量

我们将从声明和初始化 C 程序中的变量开始。

#include<stdio.h>

int main()
{
    int a[2][2], i, j;
    long determinant;

    printf("\n\nEnter the 4 elements of the array\n");
    for(i = 0; i < 2; i++)
    for(j = 0; j < 2; j++)
    scanf("%d", &a[i][j]);
}

获取矩阵元素

现在,我们将要求用户输入矩阵的元素。

printf("\n\nEnter the 4 elements of the array\n");
for(i = 0; i < 2; i++)
    for(j = 0; j < 2; j++)
    scanf("%d", &a[i][j]);

打印输入的矩阵

在获取矩阵元素后,我们将打印输入的矩阵。

printf("\n\nThe entered matrix is: \n\n");
for(i = 0; i < 2; i++)
{
    for(j = 0; j < 2; j++)
    {
        printf("%d\t", a[i][j]);   // 打印完整的行
    }
    printf("\n"); // 移动到下一行
}

计算行列式

现在我们将计算行列式。

determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\n\nDeterminant of 2x2 matrix is : %d - %d = %ld", a[0][0]*a[1][1], a[1][0]*a[0][1], determinant);

打印结果

最后,我们将打印结果。

printf("\n\nThe determinant of the 2x2 matrix is %ld.", determinant);

总结

在本实验中,我们学习了如何使用 C 语言编程计算 2x2 矩阵的行列式。我们初始化了变量,获取了矩阵元素,打印了输入的矩阵,计算了行列式,并打印了结果。

您可能感兴趣的其他 C 教程