rust - 对于错误类型的循环切片索引
问题描述
我正在尝试重新实现来自 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>`
解决方案
推荐阅读
- python - Python 正则表达式从列表中删除除字符串之外的所有内容
- c++ - 带有具有不同类型函数指针的对象的向量
- android - 在android studio中导入项目并生成.apk
- ionic-framework - Ionic ImagePicker 插件安装问题
- django - Django 如何保持其逻辑约束和数据库之间的一致性?
- r - R Shiny - 将用户输入作为全局字符串传递
- c# - 由于参数索引错误,初始化数组时出现问题
- macos - 如何在主机中查看容器内的真实进程?
- regex - 使用 PowerShell 在文件上循环搜索和替换两部分字符串,同时保留其中一个部分
- javascript - Angular 不返回预期值