如何将数字加幂? [英] How to raise a number to a power?

查看:95
本文介绍了如何将数字加幂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用尖号运算符(^)将整数提高到幂,但是得到的结果却令人惊讶,例如:

I was trying to raise an integer to a power using the caret operator (^), but I am getting surprising results, e.g.:

assert_eq!(2^10, 8);

在DuckDuckGo和Google上的搜索没有显示任何相关信息.

Searches on DuckDuckGo and Google didn't reveal anything about it.

如何在Rust中执行求幂运算?

How can I perform exponentiation in Rust?

推荐答案

插入符号运算符^不用于取幂,它是

The caret operator ^ is not used for exponentiation, it's the bitwise XOR operator.

Rust通过方法 pow 和<防止溢出的a href ="https://rust-num.github.io/num/num/pow/fn.checked_pow.html" rel ="noreferrer"> checked_pow .

Rust provides exponentiation via methods pow and checked_pow which guards against overflows.

因此,要将2提高到10的幂,请执行以下操作:

Thus, to raise 2 to the power of 10, do:

let base: i32 = 2; // an explicit type is required
assert_eq!(base.pow(10), 1024);

这篇关于如何将数字加幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆