为什么我在C ++中用^计算指数时得不到正确的结果? [英] Why am I not getting correct result when I calculate exponent with ^ in C++?
问题描述
我使用Bode的formuala计算第n个行星距太阳的距离
dist =(4 + 3 * (n-2)))/ 10
如果我以这种方式计算距离,值:
dist [2] =((4 + 3 * 1)/10.0);
dist [3] =((4 + 3 * 2)/10.0);
dist [4] =((4 + 3 * 4)/10.0);
但这样做会给我不正确的值:
矢量< double> dist(5);
for(unsigned int i = 2; i <5; i ++)
{
dist [i] =((4 + 3 * )))/ 10.0);
}
为什么如此?
由于你已经在一个循环中计算这个,你可以很容易地在方程中生成你需要的2的幂,简单的(接近你的代码)将是:
矢量< 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;
}
I am using Bode's formuala to calculate distance of nth planet from sun If I calculate the distance this way, I get the right values: But doing it this way, gives me incorrect values: Why so? The 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: In this particular instance, we initialize 这篇关于为什么我在C ++中用^计算指数时得不到正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
在这个特定的实例中,我们初始化 j
到你需要的第一个值
n-2
,然后继续乘以2,得到你需要的下一个2的幂。 p> dist = (4 + 3*(2^(n-2)))/10
dist[2] = ((4 + 3*1)/10.0) ;
dist[3] = ((4 + 3*2)/10.0) ;
dist[4] = ((4 + 3*4)/10.0) ;
vector <double> dist(5);
for (unsigned int i = 2; i < 5; i++)
{
dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;
}
^
character represents a bitwise exclusive or, not the exponential function that you expect.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;
}
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.