#include <stdio.h>
#include <string.h>
void reverse (char s[]);
void itob (int n,char s[],int b);
void itob (int n,char s[],int b){//N位一个整数,转换成B进制的字符串,存入字符串S中
int i,j,sign;
if ( ( sign = n ) < 0 ) n = - n;
i = 0;
do {
j = n % b;//任何一个数的余数不可能大于他本身
s[i++] = ( j <= 9 ) ? j + '0' : j + 'a' - 10; //j<=9 用于判定余数用2进制 8进制 或16进制表示。10:A 11:B 12:C 13:D 14:E 15:F
}while ( ( n = n / b ) > 0);
if ( sign < 0 ) s[i++] = '-' ;
s[i] = '\0' ;
reverse( s );//反向输出数字
}
void reverse (char s[]){
int i;
int len;
i = 0 ;
for ( i = ( len = strlen(s) ) ; i >=0 ; i--){
if ( s[i] != '\0') putchar( s[i] );
}
}
int main()
{
int n;
char s[5];
int b;
printf("请输入要转换的十进制数字和进制:");
scanf("%d%d",&n,&b);
if( b == 8) printf("0");
else if( b == 16) printf("0X");
else if( b == 2 ) printf("0000");
itob ( n , s , b ) ;
}
练习3-5 编写函数itob(n, s, b),用于把整数n转换成以b为基的字符串并存到字符串 c中。特 别地,itob(n, s, 16)用于把n格式化成十六进制整数字符串并存在 s中。
猜你喜欢
转载自blog.csdn.net/weixin_44127727/article/details/88092353
今日推荐
周排行