我正在尝试用 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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
Net*_*ave 10
您的代码的问题是您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
...
Run Code Online (Sandbox Code Playgroud)
您可以轻松地在没有变量的情况下完成result,这不是必需的:
fn is_prime(n: u32) -> bool {
if n <= 1 {
return false;
}
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9144 次 |
| 最近记录: |