我试图计算Rust中的素数,但有一些问题。我收到两个错误。我不明白值是如何返回主函数的。
fn main() {
let x = is_prime(25); //function calling
println!("{}", x);
}
fn is_prime(n: u32) -> bool {
let mut result: bool = for a in 2..n {
result = if n % a == 0 { false } else { true };
};
result
}
error[E0425]: cannot find value `result` in this scope
--> src/main.rs:8:9
|
8 | result = if n % a == 0 { false } else { true };
| ^^^^^^ not found in this scope
help: possible candidates are found in other modules, you can import them into scope
|
1 | use futures::future::result;
|
1 | use tokio::prelude::future::result;
|
error[E0308]: mismatched types
--> src/main.rs:7:28
|
6 | fn is_prime(n: u32) -> bool {
| ---- expected `bool` because of return type
7 | let mut result: bool = for a in 2..n {
| ____________________________^
8 | | result = if n % a == 0 { false } else { true };
9 | | };
| |_____^ expected bool, found ()
|
= note: expected type `bool`
found type `()`
您的代码的问题在于您在定义时使用变量result
...
let mut result: bool = for a in 2..n { // declared here
result = if n % a == 0 { // used here, but it is still not initialized
...
没有result
变量你可以很容易地做到,没有必要:
fn is_prime(n: u32) -> bool {
for a in 2..n {
if n % a == 0 {
return false; // if it is not the last statement you need to use `return`
}
}
true // last value to return
}
您的代码中有几个问题(忽略它不能编译):
n = 4
。除以2得到result = true
,但在下一次迭代中除以3得到result = false
n<=2
你的循环永远不会被执行,那么结果会是什么不要尝试使用任何新的语法,而是尝试将其编写为尽可能可读:
fn is_prime(n: u32) -> bool {
let limit = (n as f64).sqrt() as u32;
for i in 2..=limit {
if n % i == 0 {
return false;
}
}
true
}