Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

การแปลงตัวเลขเป็นเลขโรมัน (Number to Roman Numerals)

บทนำ

เลขโรมัน (Roman Numerals) เป็นเลขที่ไม่มีค่าตำแหน่ง (Non-positional) ใช้สัญลักษณ์บางตัวรวมกันเพื่อสร้างตัวเลขในระบบโรมัน ตัวอย่างเช่น ตัวเลข 75 สามารถแสดงได้เป็น 75 = 50 + 10 + 10 + 5 ดังนั้นเลขโรมันคือ LXXV

ในปัญหานี้ กำหนดตัวเลขหนึ่งตัวในรูปทศนิยม (Decimal) ภารกิจคือแปลงเป็นสตริงเลขโรมัน

มีสัญลักษณ์ต่างๆ และค่าของมัน ดังนี้:

IIVVIXXXLLXCCCDDCMMMMMMV'
145910405090100400500900100040005000

ด้วยตารางนี้ เราสามารถหาเลขโรมันของตัวเลขที่กำหนดได้ง่าย

อินพุตและเอาต์พุต

Input: เลขทศนิยม: 3569
Output: เลขโรมันเทียบเท่าของ 3569 คือ: MMMDLXIX

อัลกอริทึม

decToRoman(nuList, num)
Input: รายการสัญลักษณ์พร้อมค่า, ตัวเลขที่ต้องการแปลงเป็นโรมัน
Output: เลขโรมันสำหรับตัวเลขที่กำหนด

Begin
    if num ≠ 0, then
        max := หาค่าสัญลักษณ์สูงสุดที่ไม่เกินตัวเลข
        display nuList[max].symbol
        num := num - nuList[max].value
        decToRoman(nuList, num)
End

ตัวอย่างโค้ด (C++)

#include <iostream>
using namespace std;

struct numeral {
    string sym;
    int val;
};

int maxNume(numeral nu[], int num) {
    int index;
    for (int i = 0; i < 15; i++)  // 15 สัญลักษณ์ในอาเรย์
        if (nu[i].val <= num)
            index = i;  // index ของสัญลักษณ์ค่าสูงสุดที่ไม่เกินตัวเลข
    return index;
}

void decToRoman(numeral nu[], int num) {
    int max;
    if (num != 0) {
        max = maxNume(nu, num);
        cout << nu[max].sym;
        num -= nu[max].val;  // ลดตัวเลข
        decToRoman(nu, num);  // เรียกซ้ำพิมพ์สัญลักษณ์
    }
}

int main() {
    int number;
    numeral nume[15] = {{"I",1},{"IV",4},{"V",5},{"IX",9},
        {"X",10},{"XL",40},{"L",50},{"XC",90},
        {"C",100},{"CD",400},{"D",500},{"CM",900},
        {"M",1000},{"MMMM",4000},{"V'",5000}};
    cout << "Enter a decimal number: "; cin >> number;
    if (number > 0 && number <= 5000) {  // ตรวจสอบ input
        cout << "The Roman equivalent of " << number << " is: ";
        decToRoman(nume, number);
    } else {
        cout << "Invalid Input";
    }
}

ผลลัพธ์

Enter a decimal number: 3569
The Roman equivalent of 3569 is: MMMDLXIX