十进制转二进制的C语言入门编程
时间: 2024-10-13 08:17:43 浏览: 21
C语言入门-leetcode练习之第67题二进制求和.zip
十进制转换成二进制的基本思想是不断除以2并取余数,直到商为0。以下是使用C语言实现十进制转二进制的一个简单入门示例:
```c
#include <stdio.h>
#include <string.h>
// Function to convert decimal to binary
void decToBinary(int num) {
int binary[32] = {0}; // Array to store the binary digits (enough for 32-bit numbers)
int i = 0;
while (num > 0) {
binary[i++] = num % 2; // Get the remainder after dividing by 2
num /= 2; // Divide the number by 2 and remove the last digit
}
// Print the binary representation from end to beginning (reverse order)
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
int main() {
int decimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
decToBinary(decimal);
printf("\nBinary representation is: ");
return 0;
}
```
阅读全文