You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/* *
* F i l e : i t e r a t i o n . s w i f t
* C r e a t e d T i m e : 2 0 2 3 - 0 9 - 0 2
* A u t h o r : n u o m i 1 ( n u o m i 1 @ q q . c o m )
*/
/* f o r 循 环 */
func forLoop ( n : Int ) -> Int {
var res = 0
// 循 环 求 和 1 , 2 , . . . , n - 1 , n
for i in 1 . . . n {
res += i
}
return res
}
/* w h i l e 循 环 */
func whileLoop ( n : Int ) -> Int {
var res = 0
var i = 1 // 初 始 化 条 件 变 量
// 循 环 求 和 1 , 2 , . . . , n - 1 , n
while i <= n {
res += i
i += 1 // 更 新 条 件 变 量
}
return res
}
/* w h i l e 循 环 ( 两 次 更 新 ) */
func whileLoopII ( n : Int ) -> Int {
var res = 0
var i = 1 // 初 始 化 条 件 变 量
// 循 环 求 和 1 , 4 , . . .
while i <= n {
res += i
// 更 新 条 件 变 量
i += 1
i *= 2
}
return res
}
/* 双 层 f o r 循 环 */
func nestedForLoop ( n : Int ) -> String {
var res = " "
// 循 环 i = 1 , 2 , . . . , n - 1 , n
for i in 1 . . . n {
// 循 环 j = 1 , 2 , . . . , n - 1 , n
for j in 1 . . . n {
res . append ( " ( \( i ) , \( j ) ), " )
}
}
return res
}
@ main
enum Iteration {
/* D r i v e r C o d e */
static func main ( ) {
let n = 5
var res = 0
res = forLoop ( n : n )
print ( " \n for 循环的求和结果 res = \( res ) " )
res = whileLoop ( n : n )
print ( " \n while 循环的求和结果 res = \( res ) " )
res = whileLoopII ( n : n )
print ( " \n while 循环(两次更新)求和结果 res = \( res ) " )
let resStr = nestedForLoop ( n : n )
print ( " \n 双层 for 循环的遍历结果 \( resStr ) " )
}
}