天天看点

送给大家一个把阿拉伯数字与罗马数字互换的代码 -.- 仅支持4000以下的转化

基本字符 I V X L C D M
相应的阿拉伯数字表示为 1 5 10 50 100 500 1000

1》相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;

2》小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;

3》小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;

4》正常使用时、连写的数字重复不得超过三次;

5》在一个数的上面画一条横线、表示这个数扩大 1000 倍。

阿拉伯数字化为罗马数字代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cin>>n;
    while (n)
    {
        if (n>=1000)
        {
            while (n>=1000)
            {
                cout<<'M';
                n-=1000;
            }
        }
        else if (n>=500)
        {
            if (n>=900)
            {
                cout<<"CM";
                n-=900;
            }
            else
            {
                cout<<'D';
                n-=500;
            }
        }
        else if (n>=100)
        {
            if (n>=400)
            {
                cout<<"CD";
                n-=400;
            }
            else
            {
                cout<<'C';
                n-=100;
            }
        }
        else if (n>=50)
        {
            if (n>=90)
            {
                cout<<"XC";
                n-=90;
            }
            else
            {
                cout<<'L';
                n-=50;
            }
        }
        else if (n>=10)
        {
            if (n>=40)
            {
                cout<<"XL";
                n-=40;
            }
            else
            {
                cout<<'X';
                n-=10;
            }
        }
        else if (n>=5)
        {
            if (n>=9)
            {
                cout<<"IX";
                n-=9;
            }
            else
            {
                cout<<'V';
                n-=5;
            }
        }
        else if (n>=1)
        {
            if (n>=4)
            {
                cout<<"IV";
                n-=4;
            }
            else
            {
                cout<<'I';
                n-=1;
            }
        }
    }
    cout<<'\n';
    return 0;
}           

罗马数字化为阿拉伯数字代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int hua(char xx)
{
    if (xx=='I') return 1;
    else if (xx=='V') return 5;
    else if (xx=='X') return 10;
    else if (xx=='L') return 50;
    else if (xx=='C') return 100;
    else if (xx=='D') return 500;
    else return 1000;
}
int main()
{
    char luo[100];
    int shu=0;
    cin>>luo;
    int ll=strlen(luo);
    for (int i=0;i<ll;i++)
    {
        shu+=hua(luo[i]);
        if (i&&hua(luo[i])>hua(luo[i-1]))
            shu-=2*hua(luo[i-1]);
    }
    cout<<shu<<'\n';
    return 0;
}