罗马数字和阿拉伯数字的转化

阅读更多

转自 http://www.cnblogs.com/dosxp/archive/2008/08/13/1266781.html

但其中存在一些细节问题进行了修改,代码如下:

#include 
#include 

using namespace std;

int mp[100];

int val[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};

string r[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
void init()
{
    mp['I']=1;
    mp['V']=5;
    mp['X']=10;
    mp['L']=50;
    mp['C']=100;
    mp['D']=500;
    mp['M']=1000;
    return;
}
int r2n(char *str)
{
    int t,re,pre;
    re=pre=mp[str[0]];
    for(t=1;str[t]!='\0';t++)
    {
        if(mp[str[t]]<=pre)
            re+=mp[str[t]];
        else
            re=re-2*pre+mp[str[t]];
        pre=str[t];
    }

    return re;
}
string n2r(int k)
{
    int i=0;
    string re="";
    while(k>0)
    {
        while(k>=val[i])
        {
            re+=r[i];
            k-=val[i];
        }
        i++;
    }
    return re;
}
int main(){
    char *s = "IV";
    init();
    cout<< r2n(s) << endl;;
    int m = 100;
    cout << n2r(m) << endl;
    cout << n2r(6) << endl;
} 

 

 

你可能感兴趣的:(罗马数字和阿拉伯数字的转化)