题目
请编写一个C函数,该函数可以实现将一个整数转为任意进制的字符串输出
//将整数转换为10进制、2进制、16进制的数字串
#include<stdio.h>
void two(int n);
void eight(int n);
void sixteen(int n);
void two(int n)
{
int i = 0;
int arr[100];
while(n != 0)
{
arr[i] = n % 2;
n = n / 2;
i++;
}
printf("2进制:");
for(i = i - 1; i >= 0; i--)
{
printf("%d", arr[i]);
if(i % 4 == 0)
{
printf(" ");
}
}
printf("\n");
}
void eight(int n)
{
int i = 0;
int arr[100];
while(n != 0)
{
arr[i] = n % 8;
n = n / 8;
i++;
}
printf("8进制:");
for(i = i -1; i >= 0; i--)
{
printf("%d",arr[i]);
}
printf("\n");
}
void sixteen(int n)
{
int i = 0, j;
char arr[100];
while(n != 0)
{
switch(n % 16)
{
case 0:arr[i] = '0';break;
case 1:arr[i] = '1';break;
case 2:arr[i] = '2';break;
case 3:arr[i] = '3';break;
case 4:arr[i] = '4';break;
case 5:arr[i] = '5';break;
case 6:arr[i] = '6';break;
case 7:arr[i] = '7';break;
case 8:arr[i] = '8';break;
case 9:arr[i] = '9';break;
case 10:arr[i] = 'A';break;
case 11:arr[i] = 'B';break;
case 12:arr[i] = 'C';break;
case 13:arr[i] = 'D';break;
case 14:arr[i] = 'E';break;
case 15:arr[i] = 'F';break;
}
n = n / 16;
i++;
}
printf("16进制:");
for(i = i -1; i >= 0; i--)
{
printf("%c",arr[i]);
}
printf("\n");
}
int main()
{
int n;
printf("输入整数:");
scanf("%d",&n);
two(n);
eight(n);
sixteen(n);
return 0;
}