沿维度的求和数组 [英] Sum array along dimension
本文介绍了沿维度的求和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在许多语言(Fortran,Matlab / Octave,Julia等)中,诸如 sum(array,n)
之类的表达式将沿n求和一个数组的值:维度并输出一个较低维度的数组。 Rust中有等同的东西吗?
In many languages (Fortran, Matlab/Octave, Julia, etc) an expression like sum(array,n)
will sum the values of an array along the n:th dimension and outputting an array of one lower dimensionality. Is there something equivalent in Rust?
我尝试过:
fn main() {
let arr1: [f64; 5] = [1.1, 1.2, 2.3, 3.4, 4.5555];
println!("this {}", arr1.iter().sum())
}
,出现以下错误:
error[E0282]: unable to infer enough type information about `_`
--> src/main.rs:3:37
|
3 | println!("this {}", arr1.iter().sum())
| ^^^ cannot infer type for `_`
<std macros>:2:27: 2:58 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/main.rs:3:5: 3:43 note: in this expansion of println! (defined in <std macros>)
|
= note: type annotations or generic parameter binding required
推荐答案
在这种情况下,您必须明确指定元素的类型:
In this case you have to explicitly specify type of the elements:
println!("this {}", arr1.iter().sum::<f64>())
您非常亲密:)
@ E_net4建议的另一种选择是使用单独的绑定:
Another option that were suggested by @E_net4 is to use separate binding:
let res: f64 = arr1.iter().sum();
println!("this {}", res)
这篇关于沿维度的求和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文