gpt4 book ai didi

javascript - 尝试将 JS 函数转换为 C# 函数

转载 作者:行者123 更新时间:2023-12-01 03:36:34 25 4
gpt4 key购买 nike

我尝试将我的函数(使用罗马数字输入将其输出为十进制值)从 JS 转换为 C#,但不知何故我陷入困境,并且确实需要有关如何使其工作的建议。

using System;
using System.Collections.Generic;

class solution
{

static int romanToDecimal(string romanNums)
{
int result = 0;
int [] deci = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string [] roman = {"M", "CM", "D", "CD", "C", "XD", "L", "XL", "X", "IX", "V", "IV", "I"};

for (var i = 0; i < deci.Length; i++)
{
while (romanNums.IndexOf(roman[i]) == 0)
{
result += deci[i];

romanNums = romanNums.Replace(roman[i], " ");
}
}
return result;
}

static void Main()
{

Console.WriteLine(romanToDecimal("V")); //Gibt 5 aus.
Console.WriteLine(romanToDecimal("XIX")); // Gibt 19 aus.
Console.WriteLine(romanToDecimal("MDXXVI"));// Gibt 1526 aus.
Console.WriteLine(romanToDecimal("MCCCXXXVII"));// Gibt 1337 aus.
}

}

最佳答案

替换在 C# 中的工作方式不同,使用子字符串删除匹配的前几个字符:

    static int romanToDecimal(string romanNums)
{
int result = 0;
int[] deci = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
string[] roman = { "M", "CM", "D", "CD", "C", "XD", "L", "XL", "X", "IX", "V", "IV", "I" };

for (var i = 0; i < deci.Length; i++)
{
while (romanNums.IndexOf(roman[i]) == 0)
{
result += deci[i];

romanNums = romanNums.Substring(roman[i].Length);
}
}
return result;
}

关于javascript - 尝试将 JS 函数转换为 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com