我的处女作
【问题一】输出斐波那契数列。
方法一:
var fib = [Int]()
fib.append(0)
fib.append(1)
for i in 2...46{
let temp = fib[i-2] + fib[i-1]
fib.append(temp)
}
for i in 0..<47{
print(fib[i])
}
【输出】
略
方法二:
var Fib = [Int](repeatElement(0, count: 50))
Fib[0] = 0
Fib[1] = 1
for i in 2...46{
Fib[i] = Fib[i-2] + Fib[i-1]
}
for i in 0..<47{
print(Fib[i])
}
【问题二】求两数的最大公约数。
var n = 144
var m = 120
var x = max(m, n)
var y = min(m, n)
var t = x % y
while t != 0 {
x = y
y = t
t = x % y
}
print(y)
【问题三】输出星号沙漏图案,图案的一半是星号正向朝上三角形,这个三角形有h层,第一层是一个星号,以后每层比上一层多m个星号。
let h = 8
let m = 4
let k = m/2
for i in 1..
输出结果:
*****************************
*************************
*********************
*****************
*************
*********
*****
*
*****
*********
*************
*****************
*********************
*************************
*****************************
【问题四】两门课程成绩排名
方法一:
struct Marks{
var math: Int
var phys: Int
init(a: Int,b: Int){
self.math = a
self.phys = b
}
}
var stud = [Marks](repeatElement(Marks(a: 0, b:0), count: 10))
stud[0] = Marks(a: 17, b:44)
stud[1] = Marks(a: 98, b:75)
stud[2] = Marks(a: 80, b:85)
stud[3] = Marks(a: 90, b:86)
stud[4] = Marks(a: 90, b:70)
stud[5] = Marks(a: 30, b:80)
stud[6] = Marks(a: 72, b:64)
stud[7] = Marks(a: 82, b:73)
stud[8] = Marks(a: 54, b:98)
stud[9] = Marks(a: 98, b:16)
func mySort(arr:inout [Marks],cmp:(Marks,Marks)->Bool){
let cnt = arr.count
for i in 0.. $1.phys
}else{
return $0.math > $1.math
}
}
for i in 0..
方法二:
struct Marks{
var math: Int
var phys: Int
init(a: Int,b: Int){
self.math = a
self.phys = b
}
}
var stud = [Marks](repeatElement(Marks(a: 0, b:0), count: 10))
stud[0] = Marks(a: 17, b:44)
stud[1] = Marks(a: 98, b:75)
stud[2] = Marks(a: 80, b:85)
stud[3] = Marks(a: 90, b:86)
stud[4] = Marks(a: 90, b:70)
stud[5] = Marks(a: 30, b:80)
stud[6] = Marks(a: 72, b:64)
stud[7] = Marks(a: 82, b:73)
stud[8] = Marks(a: 54, b:98)
stud[9] = Marks(a: 98, b:16)
stud.sort(){
if $0.math == $1.math{
return $0.phys > $1.phys
}else{
return $0.math > $1.math
}
}
for i in 0..
输出结果:
(98,75)
(98,16)
(90,86)
(90,70)
(82,73)
(80,85)
(72,64)
(54,98)
(30,80)
(17,44)