[Swift]Function練習
Published in
3 min readAug 3, 2017
- 定義function,接受3個參數,起始值,最大值和決定數字倍數的number, 回傳運算結果 比方起始值3,最大值98,決定數字倍數的number為5時,(只包含5的倍數) 運算結果為 5 + 10 + 15 + ….. + 95
func addFiveTimes(start: Int, max: Int, times: Int) -> Int {
var sum = 0
for num in start...max where num % times == 0 {
sum += num
}
return sum
}addFiveTimes(start: 3, max: 98, times: 5)
2. 定義function,接受3個參數,起始值,最大值和決定數字倍數的number, 回傳運算結果 比方起始值3,最大值11,決定數字倍數的number為5時,(不包含5的倍數) 運算結果為 3 + 4 + 6 + 7 + 8 + 9 + 11
func addFiveTimes2(start: Int, max: Int, times: Int) -> Int {
var sum = 0
for num in start...max where num % times != 0 {
sum = sum + num
}
return sum
}addFiveTimes2(start: 3, max: 11, times: 5)
3. 奇數行的數字總合, 定義function,接受2個參數,分別代表行數和列數
func count(row: Int, column: Int) -> Int {
var sum = 0
for row in 0...row {
for col in 0...column {
if col % 2 != 0 {
let tempVal = row * col
sum = sum + tempVal
}
}
}
return sum
}count(row: 7, column: 7)
4. 所有格子的總合,除了列數>=行數的格子, 定義function,接受2個參數,分別代表行數和列數
func count2(row: Int, column: Int) -> Int {
var sum = 0
for row in 0...row {
for col in 0...column {
if row < col {
let tempVal = row * col
sum = sum + tempVal
}
}
}
return sum
}count2(row: 7, column: 7)
5. 判斷閏年
func isLeapYear(year: Int) -> Bool {
if year % 400 == 0 || year % 4 == 0 {
return true
} else {
return false
}
}isLeapYear(year: 2000)