Swift 编程打印实心矩形星形图案
本教程将讨论如何编写 Swift 程序来打印实心矩形星形图案。
星形图案是由“*”组成的序列,用于开发不同的图案或形状,如金字塔、矩形、十字形等。这些星形图案通常用于理解或练习程序流程控制,它们也有利于逻辑思维的培养。
要创建实心矩形星形图案,我们可以使用以下方法之一:
使用嵌套 for 循环
使用 init() 函数
使用 stride 函数
下面是演示:
输入
假设我们的给定输入是:
Length = 7 Width = 5
输出
期望的输出将是:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
方法 1 - 使用嵌套 For 循环
我们可以使用嵌套 for 循环创建实心矩形星形图案或任何其他图案。这里每个 for 循环处理不同的任务,例如最外层的 for 循环用于新行,嵌套的 for 循环用于在列中打印“*”。
示例
以下程序演示了如何使用嵌套 for 循环打印实心矩形星形图案。
import Foundation import Glibc // Length and width of solid rectangle // star pattern let length = 8 let width = 3 // Handle the width of the pattern for _ in 1...width{ // Handle the length of the pattern for _ in 1...length{ print("*", terminator : " ") } // New line after each row print(" ") }
输出
* * * * * * * * * * * * * * * * * * * * * * * *
在这里,在上面的代码中,我们有 length = 8 和 width = 3。现在我们使用嵌套 for 循环来打印实心矩形星形图案。最外层的 for 循环(从 1 到 3)用于处理要打印的行数,并且每一行都以新行开头。现在嵌套的 for 循环(从 1 到 8)用于处理实心矩形星形图案中要打印的列数,使用“*”。
方法 2 - 使用 init() 函数
Swift 提供了一个名为 String.init() 的内置函数。使用此函数,我们可以创建任何图案。String.init() 函数创建一个字符串,其中给定字符重复指定次数。
语法
以下是语法:
String.init(repeating:Character, count: Int)
这里,repeating 表示此方法重复的字符,count 表示给定字符在结果字符串中重复的总次数。
示例
以下程序演示了如何使用 string.init() 函数打印实心矩形星形图案。
import Foundation import Glibc // Length and width of solid rectangle // star pattern let length = 8 let width = 4 // Handle the length of pattern for _ in 1...width{ // Printing solid rectangle star pattern print(String.init(repeating: "*", count: width) + String.init(repeating:"*", count:length-width)) }
输出
******** ******** ******** ********
在这里,在上面的代码中,我们有 length = 8 和 width = 3。现在使用 String.init() 函数,我们创建了一个实心矩形星形图案。这里我们使用 for 循环(从 1 到 4),用于打印每一行。在此循环中,我们使用 String.init() 函数打印实心矩形星形图案:
String.init(repeating: "*", count: width)
根据 count 的值(即 length-width)打印“*”行,以及
String.init(repeating:"*", count:length-width)
根据 count 的值(即 length-width)打印“*”列
方法 3 - 使用 stride 函数
Swift 提供了一个名为 stride() 的内置函数。stride() 函数用于以增量或减量从一个值移动到另一个值。或者我们可以说 stride() 函数返回从起始值开始的序列,但不包括结束值,并且给定序列中的每个值都以给定量递增。
语法
以下是语法:
stride(from:startValue, to: endValue, by:count)
这里,
from − 表示要用于给定序列的起始值。
to − 表示限制给定序列的结束值
by − 表示每次迭代的步长,这里正值表示向上迭代或增量,负值表示向下迭代或减量。
示例
以下程序演示了如何使用 stride() 函数打印实心矩形星形图案。
import Foundation import Glibc // Length and width of solid rectangle // star pattern let length = 10 let width = 6 // Handle the length of pattern for _ in 1...width{ // Printing solid rectangle star pattern // Using stride() function for _ in stride(from: 1, to: length, by: 1){ print("*", terminator:" ") } print("") }
输出
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
在这里,在上面的代码中,我们有 length = 10 和 width = 6。现在我们使用嵌套 for 循环。最外层的 for 循环(从 1 到 6)用于处理要打印的行数,并且每一行都以新行开头。嵌套的 for 循环用于使用 stride() 函数打印实心矩形星形图案:
for _ in stride(from: 1, to: length, by: 1) {
print("*", terminator:" ")
}
这里的迭代从 1 到 length(即 10)开始,每次迭代增加 1,并在实心矩形图案中打印“*”。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP