public string ConvertToRoman(int num){// 定义罗马数字对应的数值 Dictionaryint, string values = new Dictionaryint, string() { { 1000, "M" }, { 900, "CM" }, { 500, "D" }, { 400, "CD" }, { 100, "C" }, { 90, "XC" }, { 50, "L" }, { 40
public string ConvertToRoman(int num)
{
// 定义罗马数字对应的数值
Dictionary<int, string> values = new Dictionary<int, string>()
{
{ 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" }
};
// 使用递归方法将整数转换为罗马数字
return ConvertToRomanRecursive(num, values);
}
public string ConvertToRomanRecursive(int num, Dictionary<int, string> values)
{
string roman = "";
foreach (KeyValuePair<int, string> pair in values)
{
while (num >= pair.Key)
{
roman += pair.Value;
num -= pair.Key;
}
}
return roman;
}
public string IntToRoman(int num)
{
int[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
string[] romans = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
StringBuilder result = new StringBuilder();
for (int i = 0; i < 13; i++)
{
while (num >= nums[i])
{
result.Append(romans[i]);
num -= nums[i];
}
}
return result.ToString();
}
}
【文章出处:滨海网页开发 http://www.1234xp.com/binhai.html 欢迎留下您的宝贵建议】