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

后端 未结 5 1399
走了就别回头了
走了就别回头了 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 02:51

    First off:

    dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;
    

    Is constant. I believe you meant to do the following:

    dist[i] = ((4 + 3*(pow(2, (i-2)))/10.0) ;
    
    0 讨论(0)
  • 2020-12-12 03:04

    Because ^ is not the power operator in C++. You can use std::pow but with double or you can do a lot of casting to make it work with int.

    0 讨论(0)
  • 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 <double> 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 <math.h>/<cmath> (C/C++, respectively).

    0 讨论(0)
  • 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<double> 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.

    0 讨论(0)
  • 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 <math.h>, or #include <cmath> and use std::pow), which returns a double; or, as other answers have suggested, for this special case you might use bit-shifting.

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