Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chuyển số La Mã sang thập phân 1-3999 trong C++


Chương trình chuyển ký tự La Mã (1-3999) sang số thập phân.

Cho một số La Mã ngẫu nhiên, chuyển thành dạng thập phân.

Ví dụ

#include<bits/stdc++.h>
using namespace std;

int value(char r) {
    if (r == 'I') return 1;
    if (r == 'V') return 5;
    if (r == 'X') return 10;
    if (r == 'L') return 50;
    if (r == 'C') return 100;
    if (r == 'D') return 500;
    if (r == 'M') return 1000;
    return -1;
}

int convert_decimal(string &str) {
    int res = 0;
    for (int i=0; i<str.length(); i++) {
        int s1 = value(str[i]);
        if (i+1 < str.length()) {
            int s2 = value(str[i+1]);
            if (s1 >= s2) res += s1;
            else { res += s2 - s1; i++; }
        } else res += s1;
    }
    return res;
}

int main() {
    string str = "MCMIV";
    cout << "Integer form:" << convert_decimal(str) << endl;
    return 0;
}

Kết quả

Integer form:1904