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

后端 未结 5 1403
走了就别回头了
走了就别回头了 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 ^ character represents a bitwise exclusive or, not the exponential function that you expect.

    Since you're calculating this in a loop already you can easily generate the powers of 2 that you need in the equation, something simple (and close to your code) would be:

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

    In this particular instance, we initialize j to the first value of n-2 that you require, then proceed to multiply it by 2 to get the next power of 2 that you require.

提交回复
热议问题