官术网_书友最值得收藏!

11. Converting numerical values to Roman

Roman numerals, as they are known today, use seven symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, and M = 1000. The system uses additions and subtractions in composing the numerical symbols. The symbols from 1 to 10 are I, II, III, IV, V, VI, VII, VIII, IX, and X. Romans did not have a symbol for zero and used to write nulla to represent it. In this system, the largest symbols are on the left, and the least significant are on the right. As an example, the Roman numeral for 1994 is MCMXCIV. If you are not familiar with the rules for Roman numerals, you should read more on the web.

To determine the Roman numeral of a number, use the following algorithm:

  1. Check every Roman base symbol from the highest (M) to the lowest (I)
  2. If the current value is greater than the value of the symbol, then concatenate the symbol to the Roman numeral and subtract its value from the current one
  3. Repeat until the current value reaches zero

For example, consider 42: the first Roman base symbol smaller than 42 is XL, which is 40. We concatenate it to the numeral, resulting in XL, and subtract from the current number, resulting in 2. The first Roman base symbol smaller than 2 is I, which is 1. We add that to the numeral, resulting in XLI, and subtract 1 from the number, resulting in 1. We add one more I to the numeral, which becomes XLII, and subtract again 1 from the number, reaching 0 and therefore stopping:

std::string to_roman(unsigned int value)
{
std::vector<std::pair<unsigned int, char const*>> roman {
{ 1000, "M" },{ 900, "CM" }, { 500, "D" },{ 400, "CD" },
{ 100, "C" },{ 90, "XC" }, { 50, "L" },{ 40, "XL" },
{ 10, "X" },{ 9, "IX" }, { 5, "V" },{ 4, "IV" }, { 1, "I" }};

std::string result;
for (auto const & kvp : roman) {
while (value >= kvp.first) {
result += kvp.second;
value -= kvp.first;
}
}
return result;
}

This function can be used as follows:

int main()
{
for(int i = 1; i <= 100; ++i)
{
std::cout << i << "\t" << to_roman(i) << std::endl;
}

int number = 0;
std::cout << "number:";
std::cin >> number;
std::cout << to_roman(number) << std::endl;
}
主站蜘蛛池模板: 内丘县| 万宁市| 河源市| 雷州市| 穆棱市| 娱乐| 诏安县| 社会| 松阳县| 霍山县| 大冶市| 临沧市| 健康| 阳泉市| 井冈山市| 三亚市| 平武县| 和静县| 哈尔滨市| 嘉峪关市| 长阳| 广灵县| 运城市| 喀喇沁旗| 德庆县| 东宁县| 吉木萨尔县| 安新县| 阳城县| 抚宁县| 荥经县| 榆社县| 荔浦县| 南漳县| 都昌县| 南投县| 双柏县| 海安县| 巫山县| 东安县| 冀州市|