标签:sign ade style str img scanf scan oid hex
练习 3-5 编写函数 itob(n, s, b),将整数n转换为以b为底的数,并将转换结果以字符的形式保存到字符串s中。例如,itob(n, s, 16)把整数n格式化成十六进制整数保存在s中。
Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s . In particular, itob(n,s,16) formats n as a hexadecimal integer in s .
代码如下
#include<stdio.h>
#include<string.h>
void reverse(char s[])//字符串倒置函数
{
int i,j,t;
for ( i = 0,j=strlen(s)-1; i <j; i++,j--)
{
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
void itob(int n,char s[],int b)
{
int sign,i;
static char b_numbers[]={"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
if ((sign=n)<0)
{
n = -n;
}
i=0;
do
{
s[i++] = b_numbers[n % b];
} while ((n/=b)>0);
if (sign<0)
{
s[i++]=‘-‘;
}
s[i]=‘\0‘;
reverse(s);
}
int main()
{
char array[100];
int n,b;
printf("请输入要转换的十进制数:");
scanf("%d",&n);
putchar(‘\n‘);
printf("转换为多少进制:");
scanf("%d",&b);
putchar(‘\n‘);
itob(n,array,b);
printf("结果为:");
for (int i = 0; array[i]!=‘\0‘; i++)
{
printf("%c",array[i]);
}
putchar(‘\n‘);
return 0;
}
运行结果

标签:sign ade style str img scanf scan oid hex
原文地址:https://www.cnblogs.com/jerryleesir/p/12933511.html