注册 登录
编程论坛 C++教室

怪了,位操作时的错误

无名可用 发布于 2010-10-08 20:04, 455 次点击
程序代码:
// Note:Your choice is C++ IDE
#include <iostream>
using namespace std;
void BuildTreeArray(int* &a,int* &c,int len);
int LowBit(int x);
void Show(const int* a,int len);
int main()
{
    int* a;
    int* c;
    int len;
    cin>>len;
    a=new int[len+1];
    c=new int[len+1];
    c[0]=0;
    for(int i=0;i<=len;i++)
    {
        a[i]=i;
    }
    BuildTreeArray(a,c,len);
    Show(c,len);
    return 0;
}

void BuildTreeArray(int* &a,int* &c,int len)
{
    c[1]=a[1];
    for(int k=2;k<=len;k++)
    {
        c[k]=0;
        for(int i=k;i>k-LowBit(k);i--)
        {
            c[k]+=a[i];
        }
    }
}

int LowBit(int x)
{
    int i=1;
    while(x&1)
    {
        x>>1;
        cout<<"*****"<<endl;
        i++;
    }
    return i*2;
    //return x&(-x);
}

void Show(const int* a,int len)
{
    for(int i=1;i<=len;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
这是我自己建的树状数组,其中LowBit()函数是用的我自己的方法,但编译程序时会有一条警告,warning:'>>'
operator has no effect:expected operator has side-effect.运行时就出现死循环了..请大家看一下..谢了
2 回复
#2
tornador2010-10-09 13:40
是这样的,在LowBit函数中你用的x>>1没有产生效力,因为对x的移位并没有对x的值产生影响,所以会出现警告,而且因为x的值没有改变,所以会出现死循环。
要写成这种形式x=x>>1;才有用。
另外,有一点我想提醒你:在编程的时候,并不是写了一些比较古怪的表达式就显示自己学的比较好,编程要朝精简、通俗易懂以便修改维护的方向去写,别写
这样的语句,在软件工程中,这些可以被认为是垃圾语句的。
希望对你有帮助。
#3
无名可用2010-10-09 21:29
谢谢
1