c语言中输出十进制数转换为二进制数后包含1的数目
1、
#include <stdio.h>
int main(void)
{
unsigned a;
puts("please input a nonnegative integers.");
printf("a = "); scanf("%u", &a);
int n = 0;
while(a)
{
if(a & 1U)
n++;
a >>= 1;
}
printf("the number of 1 in a: %u
", n);
return 0;
}
2、函数版
#include <stdio.h> int count_bits(unsigned x) { int bits = 0; while(x) { if(x & 1U) bits++; x >>= 1; } return bits; } int main(void) { unsigned a, b, c; puts("please input three nonnegative integers."); printf("a = "); scanf("%u", &a); printf("b = "); scanf("%u", &b); printf("c = "); scanf("%u", &c); printf("the number of 1 in a: %d ", count_bits(a)); printf("the number of 1 in b: %d ", count_bits(b)); printf("the number of 1 in c: %d ", count_bits(c)); return 0; }