[英]Why is this handmade square root function in Swift not returning the value, but throws the error?
Just trying to create an analog of sqrt() in Swift, but it throws.noRoot in all the matched cases.只是试图在 Swift 中创建 sqrt() 的模拟,但它在所有匹配的情况下都会抛出.noRoot。 Also I add the error.outOfBound, this is working correctly.
我还添加了error.outOfBound,它工作正常。
import UIKit
enum WrongNumber: Error {
case outOfBounds
case noRoot
}
func mySqrt(_ number: Int) throws -> Int {
if number < 1 || number > 10_000 {
throw WrongNumber.outOfBounds
}
var result = 0
for i in 1...10_000 {
if i * i == number {
result = i
} else {
throw WrongNumber.noRoot
}
}
return result
}
var number = 1000
do {
let result = try mySqrt(number)
print(result)
}
catch WrongNumber.outOfBounds {
print("You're puting a wrong number. Please try again with range from 1 to 10_000")
}
catch WrongNumber.noRoot {
print("There is no square root in your number")
}
You should return once you find it找到后应该返回
func mySqrt(_ number: Int) throws -> Int {
if number < 1 || number > 10_000 {
throw WrongNumber.outOfBounds
}
for i in 1...10_000 {
if i * i == number {
return i
}
}
throw WrongNumber.noRoot
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.