我正在尝试使用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
如何解决整数/浮点问题?
答案 0 :(得分: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
函数将复制该数组。如果平均值函数将迭代器作为参数,但似乎并非如此,那将是一种更好的方法。