snippetrustCritical
How to raise a number to a power?
Viewed 0 times
raisehowpowernumber
Problem
I was trying to raise an integer to a power using the caret operator (
How can I perform exponentiation in Rust?
^), but I am getting surprising results, e.g.:assert_eq!(2^10, 8);How can I perform exponentiation in Rust?
Solution
Rust provides exponentiation via methods
guards against overflows. Thus, to raise 2 to the power of 10, do:
The caret operator
operator.
pow and checked_pow. The latterguards 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);The caret operator
^ is not used for exponentiation, it's the bitwise XORoperator.
Code Snippets
let base: i32 = 2; // an explicit type is required
assert_eq!(base.pow(10), 1024);Context
Stack Overflow Q#51208703, score: 198
Revisions (0)
No revisions yet.