How to raise a number to a power?

前端 未结 1 1020
执笔经年
执笔经年 2021-01-01 09:12

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


        
相关标签:
1条回答
  • 2021-01-01 09:29

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

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

    0 讨论(0)
提交回复
热议问题