进制转换例题

编写一个 to_base_n() 函数,接受两个参数,且第二个参数在 2 ~ 10 范围内,然后以第二个参数中指定的进制打印第一个参数的数值。例如,to_base_n(129, 8) 显示结果 201,也就是 129 的八进制数。在一个完整的程序中测试该函数。

#include <stdio.h>
void to_base_n(unsigned long n, unsigned short t);
/* 进制转换,待转换数类型是正整数,因此使用无符号类型标识。*/
int main(void) {
    unsigned long number;
    unsigned short target;
    printf("Enter the integer and N for notation(q to quit):");
    while(scanf("%lu %hu",&number, &target) == 2){
        if(target < 2 || target > 16){
            printf("Please input N between 2 ~ 16!\n");
            printf("Enter the integer and N for notation(q to quit):");
            continue;
        }
        printf("Convert %lu to %hu notation is: ",number,target);
        to_base_n(number, target);
        putchar('\n');
        printf("Enter the integer and N for notation(q to quit):");
    }
    return 0;
}
void to_base_n(unsigned long n, unsigned short t)
{
    if(t <2 || t >16){
        printf("The function noly convert 2 ~ 16\n");
        return;
    }
    int r;
    r = n % t;
    if(n >= 2) to_base_n(n/t, t);
    if(r<=9) printf("%d",r);
	else if(r==10) putchar('A');
	else if(r==11) putchar('B');
	else if(r==12) putchar('C');
	else if(r==13) putchar('D');
	else if(r==14) putchar('E');
	else if(r==15) putchar('F');    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值