Why am I not getting correct result when I calculate exponent with ^ in C++?
I am using Bode's formuala to开发者_JS百科 calculate distance of nth planet from sun
dist = (4 + 3*(2^(n-2)))/10
If I calculate the distance this way, I get the right values:
dist[2] = ((4 + 3*1)/10.0) ;
dist[3] = ((4 + 3*2)/10.0) ;
dist[4] = ((4 + 3*4)/10.0) ;
But doing it this way, gives me incorrect values:
vector <double> dist(5);
for (unsigned int i = 2; i < 5; i++)
{
dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;
}
Why so?
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.
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
.
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) ;
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).
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.
精彩评论