Processing math: 100%

Swift 程序打印单位矩阵


在这篇文章中,我们将学习如何编写一个 Swift 程序来打印单位矩阵。单位矩阵是一个方阵,其中主对角线元素仅包含 1,其余元素为 0。例如 -

=[1000001000001000001000001]

算法

步骤 1 - 创建一个函数。

步骤 2 - 在此函数中,使用嵌套 for 循环遍历每一行和每一列。

步骤 3 - 检查行和列是否相等,然后打印 1。否则,打印 0。

步骤 4 - 声明一个变量来存储数组的大小。

步骤 5 - 调用函数并将数组大小作为参数传递给它。

步骤 6 - 打印输出。

示例

以下 Swift 程序打印单位矩阵

Open Compiler
import Foundation import Glibc // Function to create identity matrix func createIdentityMatrix(len:Int) { for x in 0..<len { for y in 0..<len { if (x == y) { print("1", terminator:" ") } else{ print("0", terminator:" ") } } print("\n") } } // Size of the matrix var size = 6 print("Identity Matrix: ") // Calling the function createIdentityMatrix(len:size)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Identity Matrix:
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1

在上面的代码中,我们创建了一个函数来打印单位矩阵。众所周知,单位矩阵的主对角线包含 1,其余元素为 0。因此,我们使用嵌套 for 循环遍历每一行和每一列,如果 x == y(表示元素为主对角线元素)则打印 1。否则,打印 0。

结论

因此,这就是我们如何打印单位矩阵的方法。单位矩阵的逆矩阵与其自身相同,单位矩阵的行列式为 1。

更新于: 2023年1月9日

149 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告