简单的生锈箱功能整数/浮点错误

问题描述 投票:0回答:1

我试图使用cargo-script运行以下生锈源文件作为脚本:

// 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

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

rust
1个回答
1
投票

问题是,平均函数想要返回与切片中的类型相同的类型。如果它允许整数,你可以计算[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函数将生成数组的副本。如果均值函数将迭代器作为参数,那么会有更好的方法,但似乎并非如此。

© www.soinside.com 2019 - 2024. All rights reserved.