數字到羅馬數字
羅馬數字是非位置制數字。一些數字組合在一起形成羅馬數字中的數字。例如,數字 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP