c语言十进制数转二进制
时间: 2024-10-13 15:01:38 浏览: 27
在C语言中,将十进制数转换为二进制数可以使用循环和位运算的方式实现。这里有一个基本的示例,展示了如何通过位操作获取每一位的值:
```c
#include <stdio.h>
#include <math.h>
// Function to convert decimal to binary
void dec_to_bin(int num) {
int binary[32]; // Assuming the maximum number is 32 bits (64-bit system)
int i = 0;
while (num > 0) {
binary[i] = num % 2; // Get the remainder after dividing by 2, which gives us the current bit
num /= 2; // Shift the number to the left, removing the least significant bit
i++;
}
// Print the binary digits in reverse order, as C arrays index from right to left
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
int main() {
int decimal_num;
printf("Enter a decimal number: ");
scanf("%d", &decimal_num);
dec_to_bin(decimal_num);
printf("\n");
return 0;
}
```
当你运行这个程序并输入一个十进制数,它会输出对应的二进制表示。
阅读全文