How to raise a number to a power?

天涯浪子 提交于 2019-12-05 13:18:54

问题


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);

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

How can I perform exponentiation in Rust?


回答1:


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

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

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);


来源:https://stackoverflow.com/questions/51208703/how-to-raise-a-number-to-a-power

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!