简单的防锈箱函数整数/浮点错误



我正在尝试使用 cargo-script 将以下 rust 源文件作为脚本运行:

// cargo-deps: statistical
extern crate statistical;
use statistical::*;
fn main() {
    let alist = [10, 20, 30, 40, 50];
    println!("mean of list: {}", mean(&alist)); // not working
}

但是,我收到以下错误:

$ cargo script mystats.rs 
    Updating crates.io index
   Compiling mystats v0.1.0 (/home/abcde/.cargo/script-cache/file-mystats-6e38bab8b3f0569c)
error[E0277]: the trait bound `{integer}: num_traits::float::Float` is not satisfied
 --> mystats.rs:7:31
  |
7 |     println!("mean of list: {}", mean(&alist));  // not working
  |                                  ^^^^ the trait `num_traits::float::Float` is not implemented for `{integer}`
  |
  = help: the following implementations were found:
            <f32 as num_traits::float::Float>
            <f64 as num_traits::float::Float>
  = note: required by `statistical::mean`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: Could not compile `mystats`.
To learn more, run the command again with --verbose.
internal error: cargo failed with status 101

如何解决这个整数/浮点数问题?

问题是 mean 函数想要返回与切片中相同的类型。如果它允许整数,你可以计算 [0, 1] 的平均值,它将返回 0(1/2 作为整数(。这就是统计强制您使用浮点类型的原因。

以下内容在我的机器上工作

// cargo-deps: statistical
extern crate statistical;
use statistical::*;
fn main() {
    let alist = [10, 20, 30, 40, 50];
    let alist_f64: Vec<f64> = alist.iter().map(|x| f64::from(*x)).collect();
    println!("mean of list: {}", mean(&alist_f64));
}

它打印这个

mean of list: 30

请注意,collect函数将创建数组的副本。如果均值函数将迭代器作为参数,会有更好的方法,但事实似乎并非如此。

最新更新