为什么我在C ++中用^计算指数时得不到正确的结果? [英] Why am I not getting correct result when I calculate exponent with ^ in C++?

查看:96
本文介绍了为什么我在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;
}



在这个特定的实例中,我们初始化 j 到你需要的第一个值 n-2 ,然后继续乘以2,得到你需要的下一个2的幂。 p>

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, 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.

这篇关于为什么我在C ++中用^计算指数时得不到正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆