首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

itob(n,s,b)将整数n变换为以b为底的数

2013-09-28 
itob(n,s,b)将整数n转换为以b为底的数。编写函数itob(n,s,b)将整数n转换为以b为底的数。 并将转换结果以字符

itob(n,s,b)将整数n转换为以b为底的数。
编写函数itob(n,s,b)将整数n转换为以b为底的数。 并将转换结果以字符的形式保存到字符串s中。
下面是代码,但是有问题,当b为16时,不能处理10-15,这个怎么和a--f对应起来。谢谢

#include <stdio.h>
#include <string.h>
void reverse(char s[])
{
    int i, j, c, len;
    len = strlen(s);
    for(j = 0, i = len - 1; j < i; ++j, --i)
    {
        c = s[j];
        s[j] = s[i];
        s[i] = c;
    }
}
void itob(int n, char s[], int b)
{
    int i;
    i = 0;
    do
    {
        s[i++] = n % b + '0';
    }
    while(n /= b);

    s[i] = '\0';

    reverse(s);
}
int main()
{
    char s[1024];
    itob(75, s, 16);  //当b为16,输出有问题?
    printf("%s\n", s);
    return 0;
}

[解决办法]

#include <stdio.h>
#include <string.h>
void reverse(char s[])
{
    int i, j, c, len;
    len = strlen(s);
    for(j = 0, i = len - 1; j < i; ++j, --i)
    {
        c = s[j];
        s[j] = s[i];
        s[i] = c;
    }
}
void itob(int n, char s[], int b)
{
    char xdigits[] = "0123456789ABCDEF";
    int i;
    i = 0;
    do
    {
        s[i++] = xdigits[n % b];
    }
    while(n /= b);
 
    s[i] = '\0';
 
    reverse(s);
}
int main()
{
    char s[1024];
    itob(75, s, 16);  //当b为16,输出有问题?
    printf("%s\n", s);
    return 0;
}

热点排行