[英]How to raise an integer to a signed integer power in Rust?
I've been using the pow()
method on integers. 我一直在对整数使用pow()
方法。 I tried raising a u32
to a negative power, which resulted in an compile error. 我试图将u32
提升到负电源,这导致了编译错误。
fn main() {
println!("{}", 2u32.pow(-1));
}
error[E0600]: cannot apply unary operator `-` to type `u32`
--> src/main.rs:2:29
|
2 | println!("{}", 2u32.pow(-1));
| ^^
This makes perfect sense, because the pow()
function does not take a signed integer as a parameter. 这是很pow()
,因为pow()
函数不将带符号整数作为参数。
Is there any way to raise an integer to a signed integer power, ideally without using an experimental nightly API? 有什么方法可以将整数提高为有符号整数次方,理想情况下无需使用实验性的夜间API? Is there any reason to only allow for unsigned integers as parameters to the pow()
function? 有什么理由只允许将无符号整数用作pow()
函数的参数?
I expect that the result would be 0.5, and the type would be a float. 我希望结果将是0.5,并且类型将是float。 I now see that a function which allows for this probably cannot be called directly on the unsigned integer, because that would result in its type changing. 我现在看到,可能无法直接在无符号整数上调用允许此功能的函数,因为这将导致其类型更改。
Perhaps there is a function which then takes both the base and power as an argument and returns a float, if such a function cannot be called directly on the integer? 如果不能直接在整数上调用此函数,也许有一个函数将基数和幂作为参数并返回浮点数?
I expect that the result [...] type would be a float 我希望结果类型为浮点型。
There is no float
type in Rust. Rust中没有float
类型。 If you refer back to The Rust Programming Language , specifically the chapter on data types , you'll see that there are two built-in floating point types: f32
and f64
. 如果回头参考Rust编程语言 ,特别是关于数据类型的章节,您会发现有两种内置的浮点类型: f32
和f64
。 Which of those should this proposed method return? 提议的方法应该返回哪些?
I expect that the result would be 0.5 我希望结果是0.5
(2u32 as f32).powi(-1)
(2u32 as f64).powi(-1)
if such a function cannot be called directly on the integer 如果此类函数不能直接在整数上调用
Any method can be called as a function : 任何方法都可以称为函数 :
f32::powi(2u32 as f32, -1)
f64::powi(2u32 as f64, -1)
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.