在函数中返回一个Bool [英] Returning a Bool in a function
本文介绍了在函数中返回一个Bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到错误缺少函数返回'Bool',但我找不出原因。
I'm getting the error "missing return in function expected to return 'Bool'" but I can't figure out why.
func isPrime(_ number: Int) -> Bool {
for primeDivisors in 2..<number {
if number % primeDivisors == 0 {
return true
} else {
return false
}
}
}
isPrime(13)
推荐答案
您的主要检查器不正确,因为循环的第一次迭代会返回一个值。您必须经过整个循环才能确定数字是否为素数。
Your prime checker is incorrect, because the very first iteration of the loop returns a value. You have to go through the entire loop before deciding that the number is prime.
func isPrime(_ number: Int) -> Bool {
for primeDivisors in 2..<number {
if number % primeDivisors == 0 {
return false
}
}
return true
}
请注意,此代码效率低下,因为它继续检查整除次数是必要的:您可以在达到数字
的平方根时停止检查。
Note that this code is inefficient, because it continues checking divisibility more times than it is necessary: you can stop checking upon reaching square root of number
.
这篇关于在函数中返回一个Bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文