數字轉羅馬數字
羅馬數字是非位置數字。有一些數字放在一起,形成一個羅馬數字。例如,數字 75 可以表示為 75 = 50 + 10 + 10 + 5,因此羅馬數字為 LXXV。
此問題中以十進位制格式提供一個數字,我們的任務是將其轉換為羅馬數字字串。
有不用的符號和對應的值,如下所示。
I | IV | V | IX | X | XL | L | XC | C | CD | D | CM | M | MMMM | V’ |
1 | 4 | 5 | 9 | 10 | 40 | 50 | 90 | 100 | 400 | 500 | 900 | 1000 | 4000 | 5000 |
使用此表格,我們可以輕鬆地找出給定數字的羅馬數字。
輸入和輸出
Input: Decimal number: 3569 Output: The Roman equivalent of 3569 is: MMMDLXIX
演算法
decToRoman(nuList, num)
輸入:帶值、需要轉換的羅馬數字的數字列表。
輸出:給定數字的羅馬數字。
Begin if num ≠ 0, then max := get maximum numeral value, not greater than number display the nuList[max].symbol num := num – nuList[max].value decToRoman(nuList, num) End
示例
#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 numerals in array if(nu[i].val<= num) index = i; //gretest value numeral index, not greater than number 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; //decrease number decToRoman(nu, num); //recursively print numerals } } 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) { //checking input number 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
廣告