C语言编程入门必做题-2~16进制转换

来源:互联网 发布:数据nba 编辑:程序博客网 时间:2024/05/20 00:15

将输入的10进制数转换成2~16进制数
补充说明一句,这是最傻帽的算法了,就是一个个加上去而已……

希望抛砖引玉了,清高是不吝指点,谢谢!!

/**//*
转载请保留此信息

作者:shaoshaoh
Blog:http://blog.csdn.net/shaoshaoh 
*/

#include <stdio.h>
#
include <stdlib.h>
#
include <math.h>
long get_int_num(char * del);

int main(int argc
, char *argv[])
{
    long base
, num, index;
    char 
*nbase;
    int bit;
    base 
=get_int_num("please insert base:");
    
if (base > 16 || base < 2)
    {
        
printf("Error!");
        
return 0;
    }
    num 
= get_int_num("please insert a decimal num:");
 
    
/*+2是因为这个取整办法是四舍五入的,比如
     * log(10)/log(2)结果是3.xx取整后结果是3
     * 而10的二进制数是4位的,还有一个字符串
     * 结尾符,所以…
*/
    bit 
= (int)(log(num)/log(base)) + 2;
    
    nbase 
= (char * )malloc(sizeof(char)*bit);
    
for ( index = 0; index < bit; index++)
        nbase[index]
='0';
        
    nbase[bit
-1= 0/*字符串结束符*/

    
while(num > 0)
    {
        index 
= bit-2;
        nbase[index]
++;
        
if (nbase[index] >'9') nbase[index]='A';
        num
--;
        
while(nbase[index]-'0'==base)
        {
            nbase[index]
='0';
            index
--;
            nbase[index]
++;
        }
    }
    
printf("The answer is : %s ",nbase);
    free(nbase);
}
long get_int_num(char 
* del)
{
    long n;
    
printf(del);
    
printf(" ");
    scanf(
"%d", &n);
    
return n;
}