C#将大阿拉伯数字转换为罗马数字?

时间:2018-12-19 15:12:29

标签: c# .net winforms

我有一个程序。我正在编写一个程序,它将大的阿拉伯数字转换为罗马数字(> = 4000)From this tutorial。该程序使用以下代码将整数转换为罗马数字。

// Map digits to letters.
private string[] ThouLetters = { "", "M", "MM", "MMM" };
private string[] HundLetters =
{ "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
private string[] TensLetters =
{ "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
private string[] OnesLetters =
{ "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
private string ArabicToRoman(int arabic) {
    // See if it's >= 4000.

    if (arabic >= 4000)
{
    // Use parentheses.
    int thou = arabic / 1000;
    arabic %= 1000;
    return "(" + ArabicToRoman(thou) + ")" +
        ArabicToRoman(arabic);
}
    // Otherwise process the letters.
string result = "";

// Pull out thousands.
int num;
num = arabic / 1000;
result += ThouLetters[num];
arabic %= 1000;

// Handle hundreds.
num = arabic / 100;
result += HundLetters[num];
arabic %= 100;

// Handle tens.
num = arabic / 10;
result += TensLetters[num];
arabic %= 10;

// Handle ones.
result += OnesLetters[arabic];

    return result;
 }

该程序当前正在运行。但是,如果阿拉伯数字大于3999,则将它们写为(如果我输入5000,它将返回)(v)。。我需要它如下。如果输入5000,它将返回到(5)M。或在(5)中。现在我试着尝尝,但没有帮助。...

    // See if it's >= 4000.
if (arabic >= 4000)
{
    // Use parentheses.
    int thou = arabic / 1000;
    string s = thou.ToString();
    arabic %= 1000;
    return "(" + s + ")M" +
        ArabicToRoman(arabic);
}

我也尝试了其他方法。但这没用...我该如何解决这个问题? 谢谢。

1 个答案:

答案 0 :(得分:0)

您的第二个代码示例对我来说很好用,但是对于大于3999的数字,您不需要递归的情况,您只需在您的数千个部分添加一个if语句即可:

// Pull out thousands.
var num = arabic / 1000;
if (num > 3) result += $"({num})M";
else result += ThouLetters[num];
arabic %= 1000;