class Fraction {
var numweator = 0 //分子
var denomator = 0 //分母
static func getMaxYue(num:Int,deno:Int) -> Int {
guard num != 0 && deno != 0 else {
return -1
}
//得到两个绝对值
let numAbs = abs(Int32(num))
let denoAbs = abs(Int32(deno))
//得到绝对值中最小的那个
let min = numAbs > denoAbs ? denoAbs : numAbs
//定义变量,表示最大公约数
var maxYue:Int32 = 1
for item in 1...min {
if numAbs % item == 0 && denoAbs % item == 0 {
maxYue = item
}
}
return Int(maxYue)
}
func show() -> Void {
guard denomator != 0 else {
print("分母不能为零!")
return
}
let max = Fraction.getMaxYue(num: numweator, deno: denomator)
if denomator > 0 && numweator > 0 {
print("\(numweator/max)/\(denomator/max)")
} else if denomator > 0 && numweator < 0 {
print("\(numweator/max)/\(denomator/max)")
} else if denomator < 0 && numweator > 0 {
print("-\(numweator/max)/\((-denomator)/max)")
} else if denomator < 0 && numweator < 0 {
print("\(-numweator/max)/\(-denomator/max)")
} else if numweator == 0 {
print("0")
}
}
}
var f = Fraction()
f.numweator = -4
f.denomator = 1
f.show()
Swift表示分数
最新推荐文章于 2020-10-27 20:57:41 发布