http://9195095.blog.51cto.com/9185095/1705669 2015 问题: 编写一个函数itob(int n,char s[], int b),将整数n转换为以b进制的数。保存到s中。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <stdio.h>
void reverse( char *left, char *right)
{
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
void itob( int n, char s[], int b)
{
char *start;
char *end;
start = s;
while (n)
{
if (b <= 10)
*s = (n % b) + '0' ;
else if (b == 16)
*s = "0123456789abcdef" [n % b];
s++;
n /= b;
}
*s = '\0' ;
end = s - 1;
reverse(start, end);
}
int main()
{
char arr[20];
int b = 0;
int num = 0;
printf ( "请输入要转换的数 和几进制数\n" );
scanf_s( "%d,%d" , &num, &b);
itob(num, arr, b);
printf ( "%s\n" , arr);
return 0;
}
|
|