types - 无法正确获取 Rust 类型

标签 types rust

use std::num::Float;

fn main() {
    for i in 1..101 {
        euler(i)
    }
}

fn euler(x: i32){
    let n: i32 = x;
    let e: f64 = (1.0+(1.0/n)).powi(n);

    println!("Euler's number where n = {} is {}", n, e);
}

我有这段代码,但无法编译。我是 Rust 的新手,非常感谢您的帮助!

最佳答案

让我们看一下错误信息:

<anon>:11:28: 11:29 error: mismatched types:
 expected `_`,
    found `i32`
(expected floating-point variable,
    found i32) [E0308]
<anon>:11     let e: f64 = (1.0+(1.0/n)).powi(n);
                                     ^

在这里,Rust 有非常好的信息:您需要提供一个浮点变量,而不是一个整数变量:

let e: f64 = (1.0+(1.0/n as f64)).powi(n);
// HERE                ^~~~~~~~

关于types - 无法正确获取 Rust 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29177894/

相关文章:

types - 无开销的开关接口(interface)实现

python - 类型错误 : a float is required

rust - Rust 中两种风格的文档注释有什么区别? (///对//!)

线程的 Rust 生命周期问题

rust - 如何在过程宏中指定条件代码

c# - 这是对泛型的滥用吗?

sql - 对于增值税,SQL Server 字段大小声明的正确 Decimal(p, s) 精度和小数位数是多少?

python - 当列包含字符串值时 pandas DataFrame.sum 的奇怪行为

rust - 我将如何在 Rust 中创建和使用字符串来字符串化 Hashmap?

rust - 如何将 u8 切片复制到 u32 切片?