用C语言写一个进制转换器
时间: 2023-12-29 17:48:38 浏览: 63
以下是将十进制数转换为二进制、八进制、十六进制的示例代码:
```c
#include <stdio.h>
void toBinary(int num) {
int binary[50], i = 0;
while (num > 0) {
binary[i] = num % 2;
num /= 2;
i++;
}
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
}
void toOctal(int num) {
int octal[50], i = 0;
while (num > 0) {
octal[i] = num % 8;
num /= 8;
i++;
}
printf("Octal: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", octal[j]);
}
printf("\n");
}
void toHexadecimal(int num) {
char hex[50];
int i = 0, rem;
while (num > 0) {
rem = num % 16;
if (rem < 10) {
hex[i] = rem + 48;
} else {
hex[i] = rem + 55;
}
num /= 16;
i++;
}
printf("Hexadecimal: ");
for (int j = i - 1; j >= 0; j--) {
printf("%c", hex[j]);
}
printf("\n");
}
int main() {
int num;
printf("Enter a decimal number: ");
scanf("%d", &num);
toBinary(num);
toOctal(num);
toHexadecimal(num);
return 0;
}
```
示例输出:
```
Enter a decimal number: 123
Binary: 1111011
Octal: 173
Hexadecimal: 7B
```
阅读全文