The Fourth Dimension Space

枯叶北风寒,忽然年以残,念往昔,语默心酸。二十光阴无一物,韶光贱,寐难安; 不畏形影单,道途阻且慢,哪曲折,如渡飞湍。斩浪劈波酬壮志,同把酒,共言欢! -如梦令

POJ 1546 Basically Speaking-数进制转换

原题链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=1546

题目的意思很简单,给你一个n进制的数,让你把它转换成m进制,但是有一个限制,如果输出的数字大于7为的话无法在计算器上显示,所以要输出ERROR;

说说做这道题的体会吧,方法很easy,不过感觉代码写的长了点,第一个函数里用了map容器,后来发现其实并没有减少工作量,所以第二的函数里就干脆没使用了 O(∩_∩)O~
所犯的几个错误是 转换成desbase进制是,while循环里应该是num!=0,刚开始的时候写成了num/desbase!=0;呵呵
其次是发现不能在全局状态下往容器里面添加元素。害我总是编译不了,查了半天才知道的。。。

下面是我的代码:
#include <iostream>
#include
<cstring>
#include
<algorithm>
#include
<cmath>
#include
<map>
using namespace std;


map
<char,int>amap;
char temp[100];
int oribase;
int desbase;



int convet(char a[],int oribase)
{
    
int len=strlen(a);
    
int i;
    
int result=0;
    
for(i=0;i<len;i++)
    
{
        result
+=amap[a[len-1-i]]*pow((double)oribase,i);
    }

    
return result;
}


void convet2(int num,int desbase)
{
    
char test[100];
    
int i=0;
    
int testnum;
    
int len;
    
while(num!=0)
    
{
        testnum
=num%desbase;
        num
=num/desbase;
        
if(testnum==15)
            test[i]
='F';
        
else    if(testnum==14)
            test[i]
='E';
        
else if(testnum==13)
            test[i]
='D';
        
else if(testnum==12)
            test[i]
='C';
        
else if(testnum==11)
            test[i]
='B';
        
else if(testnum==10)
            test[i]
='A';
        
else if(testnum==9)
            test[i]
='9';
        
else if(testnum==8)
            test[i]
='8';
        
else if(testnum==7)
            test[i]
='7';
        
else if(testnum==6)
            test[i]
='6';
        
else if(testnum==5)
            test[i]
='5';
        
else if(testnum==4)
            test[i]
='4';
        
else if(testnum==3)
            test[i]
='3';
        
else if(testnum==2)
            test[i]
='2';
        
else if(testnum==1)
            test[i]
='1';
        
else if(testnum==0)
            test[i]
='0';
        i
++;
    }

    test[i]
='\0';
    reverse(test,test
+strlen(test));
    strcpy(temp,test);
}


int main ()
{
    amap[
'0']=0;amap['1']=1;amap['2']=2;amap['3']=3;
    amap[
'4']=4;amap['5']=5;amap['6']=6;amap['7']=7;
    amap[
'8']=8;amap['9']=9;amap['A']=10;amap['B']=11;
    amap[
'C']=12;amap['D']=13;amap['E']=14;amap['F']=15;
    
int midresult;
    
int len;
    
while(scanf("%s%d%d",temp,&oribase,&desbase)!=EOF)
    
{
        
        midresult
=convet(temp,oribase);
        convet2(midresult,desbase);
        len
=strlen(temp);
        
if(len>7)
        
{

            printf(
"  ERROR\n");

        }

        
else
            printf(
"%7s\n",temp);
    }

    
return 0;


}

posted on 2009-02-19 23:50 abilitytao 阅读(1039) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理