首页 > 解决方案 > 对于错误类型的循环切片索引

问题描述

我正在尝试重新实现来自 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]

在锈中:

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

标签: rust

解决方案


推荐阅读