我正在尝试重新实现HackerRank中的编码问题,这在Rust中的Python中非常容易。
输入和目标是这样的:
#10 * 1 + 40 * 2 + 30 * 3 + 50 * 4 + 20 + 5 480
#------------------------------------------ = --- = 32.00
# 1 + 2 + 3 + 4 + 5 15
分子是first_array[nth]
* second_arry[nth]
的总和除以second_array
各项的总和-它返回加权均值(提供了加权)。
我的Python看起来像这样:
for i in range(0, n):
numerator += fl[i] * sl[i]
denominator += sl[i]
在Rust中:
fn weighted_avg(fl: Vec<f64>, sl: Vec<f64>) -> f64 {
let mut n = fl.len() as u32;
let mut numerator = 0f64;
let mut denominator = 0f64;
for i in 1..n {
denominator += sl[i];
numerator += fl[i] * &denominator;
}
numerator / denominator
}
我得到的错误是:
error[E0277]: the trait bound `u32: std::slice::SliceIndex<[f64]>` is not satisfied
--> src/lib.rs:7:24
|
7 | denominator += sl[i];
| ^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[f64]>` is not implemented for `u32`
= note: required because of the requirements on the impl of `std::ops::Index<u32>` for `std::vec::Vec<f64>`
error[E0277]: the trait bound `u32: std::slice::SliceIndex<[f64]>` is not satisfied
--> src/lib.rs:8:22
|
8 | numerator += fl[i] * &denominator;
| ^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[f64]>` is not implemented for `u32`
= note: required because of the requirements on the impl of `std::ops::Index<u32>` for `std::vec::Vec<f64>`