c_cpp 十进制到二进制并计数1的数量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 十进制到二进制并计数1的数量相关的知识,希望对你有一定的参考价值。

#include <stdio.h>

int main() {

	int num,
		decimal_num,
		reminder,
		base = 1,
		binary = 0,
		no_of_1s = 0;

	printf("Enter a decimal Number: ");
	scanf("%d", &num);

	decimal_num = num;

	while (num > 0) {

		reminder = num % 2;
		if (reminder == 1) {
			no_of_1s++;
		}

		binary = binary + reminder * base;

		num = num / 2;
		base = base * 10;
	}


	printf("Input number is = %d\n", decimal_num);
	printf("Ints binary number is %d\n", binary);
	printf("No.of 1's in the binary is = %d\n", no_of_1s);

	return 0;
}

以上是关于c_cpp 十进制到二进制并计数1的数量的主要内容,如果未能解决你的问题,请参考以下文章