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

后端 未结 5 1412
走了就别回头了
走了就别回头了 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条回答
  •  猫巷女王i
    2020-12-12 03:12

    For one, there's ^ means "xor", not "power of". For another, you're calculating a constant value (You did 3-2 instead of i-2). However, since you want a power of two, bit-shifting can work your way. ("1 << X" works out as "2^X")

    vector  dist(5);
    
    for (unsigned int i = 2; i < 5; i++) {
       dist[i] = ((4 + 3*(1 << (i - 2)))/10.0) ;
    }
    

    For other bases, you need the pow() library function found in / (C/C++, respectively).

提交回复
热议问题