杭电OJ2031 C++ 将10进制的数转换成R进制输出

思路:难点在于如何将10-15转换成A-F,我的方法是设立一个字符数组,里面的16个元素为0-F,将我要转换的字符放入这个数组中就得到了转换后的元素,在测量字符数组的长度时,s[i]=‘\0’,因为在字符数组只有遇到\0才会结束。

#include<stdio.h>
#include<string.h>
int main()
{
    char s[10000];
    char a[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    int n,m,i,b,l;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n<0)
        {
            n=-n;
            i=0;
            b=0;
            do
            {
            b=n%m;
            n=n/m;
            s[i++]=a[b];   //辗转相除法求转换成R进制输出的数
            }while(n!=0);
            s[i]='\0';  //s[i]必须置零,才能测出整个字符串的长度
            printf("-");
            for(i=strlen(s)-1;i>=0;i--)
                printf("%c",s[i]);
            printf("\n");
            //printf("%c\n",s[0]);
        }
        else
        {
            i=0;
            do
            {
            b=n%m;
            n=n/m;
            s[i++]=a[b];
            }while(n!=0);
            s[i]='\0';
            for(i=strlen(s)-1;i>=0;i--)
                printf("%c",s[i]);
            printf("\n");
            //printf("%c\n",s[0]);
        }
    }
    return 0;
}
发布了28 篇原创文章 · 获赞 7 · 访问量 1177

猜你喜欢

转载自blog.csdn.net/weixin_44433678/article/details/97620949