20.赋值运算符与表达式

在赋值表达式中,如果表达式左边的变量重复出现在表达式的右边,如:

i=i+2

则可以将这种表达式缩写为下列形式:

i +=2

其中的运算符+=称为赋值运算符。

下面的函数bitcount统计其整型

/*  bitcount函数:统计x中值为1的二进制位数  */
int bitcount(unsigned x)
{
	int b;
	for (b=0;x !=0; x>>=1)
        if (x& 01)
            b++;
    return b;
}

这里将x声明为无符号类型是为了保证将x右移时,无论该程序在什么机器上运行,左边空出的位都用0填补。

练习2-9

#include 
#include 
int bitcount(unsigned x);
int main()
{
    int a, b;
    a=7;
    b=bitcount(a);
    printf("%d\n", b);
    system("pause");
    return 0;
}
int bitcount(unsigned x)
{
    int b;
    for (b=0; x!=0; b++)
        x&=(x-1);
    return b;
}

下面是程序运行结果:

20.赋值运算符与表达式_第1张图片

 

你可能感兴趣的:(c++,c语言,算法)