6-4 exercise 3-5 (10分)
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 s as a hexadecimal integer in s.
答案:我自己的
void reverse(char s[])
{
int m = 0, n = 0;
for (; s[m] != ‘\0’; m++);//m即为几个字符
char te;
m -= 1;
while (n < m)
{
te = s[n];
s[n] = s[m];
s[m] = te;
m–; n++;
}
}
void itob(int n, char s[], int base)
{
char digits[] = “0123456789abcdefghijklmnopqrstuvwxyz”;
int sign = 1;
int i=0;
if (n < 0) {
n = -n;
sign = -1;
}
for (; n > 0; n /= base)
{
s[i++] = digits[n % base];
}
if (sign == -1)
s[i++] = ‘-’;
s[i] = ‘\0’;
reverse(s);
}