不用临时变量,实现两个数的交换
#include<stdio.h>
void main()
{
int a = 10;
int b = 20;
printf("原先:a=%d b=%d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("转换:a=%d b=%d\n", a, b);
printf("------------------------\n");
int c = 10;
int d = 20;
printf("原先:c=%d d=%d\n", c, d);
c = c ^ d;
d = c ^ d;
c = c ^ d;
printf("转换:c=%d d=%d\n", c, d);
}
对于一个8bit(1字节)的变量,求其二进制里出现了多少个1
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int count(int ch)
{
int i = 0;
while(ch)
{
i++;
ch = ch & (ch - 1);
}
return i;
}
void printfBin(int ch)
{
if (ch)
{
printfBin(ch / 2);
printf("%d", (ch % 2));
}
else
return 0;
}
void main()
{
int ch;
int i;
printf("请输入一个数(0-255之间):\n");
scanf("%d", &ch);
printf("%d的二进制为:", ch);
printfBin(ch);
printf("\n");
i = count(ch);
printf("1的个数为:%d\n", i);
}
|