這是一個完成的羅馬到十進制數字轉換器。可以避免if-else
Dictionary<char,int> nTrans = new Dictionary<char,int>();
nTrans.Add('I',1);
nTrans.Add('V', 5);
nTrans.Add('X', 10);
nTrans.Add('L', 50);
nTrans.Add('C', 100);
nTrans.Add('D', 500);
nTrans.Add('M', 1000);
string rNum = "XV";
int dNum = 0;
for (int i = 0; i < rNum.Length; i++)
{
if (i < rNum.Length-1)
{
if (nTrans[rNum[i]] < nTrans[rNum[i + 1]])
{
dNum -= nTrans[rNum[i]];
}
else
{
dNum += nTrans[rNum[i]];
}
}
else
{
dNum += nTrans[rNum[i]];
}
}
但我無法弄清楚如何使用這個if-else語句逃脫
if (i < rNum.Length-1)
{
//Code
}
else
{
dNum += nTrans[rNum[i]];
}
任何建議,我怎麼能避免使用它?這個問題只是爲了優化和提高我的編程技能!
我不知道你是否應該問這個說_Code Review_ SE? – MickyD
'dNum = nTrans [rNum [i]]
Spectarion
@Spectarion雖然你消除了一個明確的if,但你的代碼與原始代碼具有相同的源代碼_cyclomatic complexity_。 http://www.ndepend.com/docs/code-metrics#CC – MickyD