如何对罗马数字进行数学运算

时间:2017-06-08 06:36:30

标签: javascript asp.net

如何对asp.net中的加法,减法,乘法和除法等罗马数字进行数学运算c#

1 个答案:

答案 0 :(得分:-1)

步骤1:将您的罗马数字转换为数字。

以下是从罗马转换为数字的示例。

private enum RomanDigit
{
    I = 1,
    V = 5,
    X = 10,
    L = 50,
    C = 100,
    D = 500,
    M = 1000
}

public static int RomanToNumbers(string roman)
{
    roman = roman.ToUpper().Trim();
    if (roman == "N") return 0;

    int ptr = 0;
    ArrayList values = new ArrayList();
    int maxDigit = 1000;
    while (ptr < roman.Length)
    {
        char numeral = roman[ptr];
        int digit = (int)Enum.Parse(typeof(RomanDigit), numeral.ToString());

        int nextDigit = 0;
        if (ptr < roman.Length - 1)
        {
            char nextNumeral = roman[ptr + 1];
            nextDigit = (int)Enum.Parse(typeof(RomanDigit), nextNumeral.ToString());

            if (nextDigit > digit)
            {
                maxDigit = digit - 1;
                digit = nextDigit - digit;
                ptr++;
            }
        }

        values.Add(digit);
        ptr++;
    }

    int total = 0;
    foreach (int digit in values)
        total += digit;

    return total;
}

步骤2:现在使用以下代码来获取上述方法的值。

string data1 = "CDXIX";
string data2 = "CCXXII";
int value1 = RomanToNumbers(data1); //returns 419
int value2 = RomanToNumbers(data2); //returns 222

步骤3:现在执行诸如求和,减法,乘法或除法等操作。

int result = value1 + value2; //641

步骤4:使用以下方法将数字转换为罗马

public static string ToRoman(int number)
{
    if ((number < 0) || (number > 3999)) throw new ArgumentOutOfRangeException("insert value betwheen 1 and 3999");
    if (number < 1) return string.Empty;            
    if (number >= 1000) return "M" + ToRoman(number - 1000);
    if (number >= 900) return "CM" + ToRoman(number - 900); //EDIT: i've typed 400 instead 900
    if (number >= 500) return "D" + ToRoman(number - 500);
    if (number >= 400) return "CD" + ToRoman(number - 400);
    if (number >= 100) return "C" + ToRoman(number - 100);            
    if (number >= 90) return "XC" + ToRoman(number - 90);
    if (number >= 50) return "L" + ToRoman(number - 50);
    if (number >= 40) return "XL" + ToRoman(number - 40);
    if (number >= 10) return "X" + ToRoman(number - 10);
    if (number >= 9) return "IX" + ToRoman(number - 9);
    if (number >= 5) return "V" + ToRoman(number - 5);
    if (number >= 4) return "IV" + ToRoman(number - 4);
    if (number >= 1) return "I" + ToRoman(number - 1);
    throw new ArgumentOutOfRangeException("something bad happened");
}

步骤5:现在再次从数字转换为罗马语以获得结果

string output = ToRoman(result); //your output "DCXLI"