qfedu-c-level/day5/homework/h9.c

27 lines
655 B
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 请编程, 输入一个整数输出它的二进制数中1和0的个数。
#include <stdio.h>
int main()
{
int inputNum;
int temp = 0, zeroCnt = 0, oneCnt = 0;
printf("请输入一个整数: ");
scanf("%d", &inputNum);
for (int i = 0; temp < inputNum; i++)
{
temp = 1 << i;
// if ((inputNum & temp) == temp)
// oneCnt++;
// else if ((inputNum | ~temp) == ~temp)
// zeroCnt++;
if (inputNum & temp)
oneCnt++;
else
zeroCnt++;
}
printf("%d 的二进制中 1 有 %d 个, 0 有 %d 个", inputNum, oneCnt, zeroCnt);
return 0;
}