AHU_OJ 434

题目是任意进制之间的转换.

解答思路:

  将任意进制a转到十进制,再将十进制转到任意进制b.这个方法比较的直接......

#include "stdio.h"
#include "string.h"
#include "math.h"
#include "stdlib.h"
#define NUM 62
#define INPUTNUM 50
/*初始化串表,用来方便查询字符对应的数字.如A对应数组下表10*/
void init_string(char *s){
    int i;
    char c;
    c='0';
    for(i=0;i<10;i++){
        s[i]=c;
        c=c+1;
    }
    c='A';
    for(i=10;i<36;i++){
        s[i]=c;
        c=c+1;
    }
    c='a';
    for(i=36;i<62;i++){
        s[i]=c;
        c=c+1;
    }
}
/*任意进制转为十进制*/
int anytoten(char *t,char *s,int any){            //*t为任意进制串,s为串表,any为进制数    将任意制转为十进制
    int i=0,j=0,k,sum=0;
    k=strlen(t)-1;
    while(t[i]!=''){
        for(j=0;j<NUM;j++)
            if(t[i]==s[j])
                sum=sum+j*pow(any,k);
        k--;
        i++;
    }
    return sum;
}
/*十进制转为指定的(any)进制*/
void *tentoany(char *t,char *s,int any,int n){    //*t为转到的进制串,s为串表,any为转到的进制
    int shang=1,yushu;
    int i=0;
    while(shang!=0){
        shang=n/any;
        yushu=n%any;
        n=shang;
        t[i++]=s[yushu];
    }
    t[i]='';
}
int main(){
    int i;
    char s[NUM],c;
    char input[INPUTNUM];
    int ans,from_hex,to_hex;
    i=0;
    init_string(s);
    printf("Enter the number string
");
    while((c=getchar())!='
'){
        input[i++]=c;
    }
    input[i]='';
    i=0;
    printf("The pre_hex and the to_hex
");
    scanf("%d%d",&from_hex,&to_hex);
    ans=anytoten(input,s,from_hex);
    tentoany(input,s,to_hex,ans);
    i=0;
    while(input[i++]!='');
    i=i-2;
    printf("The answer of %d(hex) is
",to_hex);
    while(i>=0)
        printf("%c",input[i--]);
    system("pause");
}
原文地址:https://www.cnblogs.com/brillliu/p/3544761.html