将整数转换为10进制、2进制、16进制的数字串

来源:互联网 发布:mac磁盘工具抹掉失败 编辑:程序博客网 时间:2024/05/16 19:37

将整数转换为10进制、2进制、16进制的数字串,采用函数调用方法。


#include <stdio.h>


void to_binary(int n);              //将整数转换为二进制
void to_dec(int n);                   //将整数转换为十进制
void to_hex(int n);                   //将整数转换为十六进制

int main()
{
        int a;

        printf("Please enter a integer number(q to quit):\n");

        while(scanf("%d",&a) == 1 )
        {
                printf("binary output:");
                to_binary(a);
                printf("\n");
            printf("dec output:");
                to_dec(a);
                putchar('\n');
                printf("hex output:");
                to_hex(a);
                putchar('\n');
        }


    return 0;
}


void to_binary(int n)
{
        int i;

        i = n % 2;
        if(n >= 2)
                to_binary(n / 2);              //递归,反序输出
        putchar('0'+ i );                      //加‘ 0’,以字符型输出

        return ;
}


void to_dec(int n)
{
        int i;
         
        i = n % 10;
        if( n >= 10 )
                to_dec( n / 10);
        putchar('0' + i);

        return ;
}


void to_hex(int n)
{
        int i;
         
        i = n % 16;
        if( n >= 16 )
                to_hex( n / 16);
        if( i > 9)
                putchar('0' + i + 7);            //超过9的数字输出字母,如A、B、C等等,将7换为39可以小写输出
        else 
        putchar('0' + i);

        return ;
}

示例输出:

Please enter a integer number(q to quit):
12
binary output:1100
dec output:12
hex output:C
78
binary output:1001110
dec output:78
hex output:4E


0 0