Why am I not getting correct result when I calculate exponent with ^ in C++?

后端 未结 5 1411
走了就别回头了
走了就别回头了 2020-12-12 02:39

I am using Bode\'s formuala to calculate distance of nth planet from sun

dist = (4 + 3*(2^(n-2)))/10

If I calculate the distance this way,

5条回答
  •  盖世英雄少女心
    2020-12-12 03:13

    The ^ operator, in C++ (and several other languages) means "exclusive or", not "raise to power".

    C++ does not have a "raise to power" operator; you need to use the 2-argument function pow (you can #include the old C-generation , or #include and use std::pow), which returns a double; or, as other answers have suggested, for this special case you might use bit-shifting.

提交回复
热议问题