發問時間: 電腦與網際網路程式設計 · 6 年前

C# 要如何改寫

private string MathCount (string a, string b, string sym)

{

int Result = 0;

int iValue1 = Convert.ToInt32(a);

int iValue2 = Convert.ToInt32(b);

switch (sym)

{

case "+":

Result = iValue1 + iValue2;

break;

case "-":

Result = iValue1 - iValue2;

break;

case "*":

Result = iValue1 * iValue2;

break;

case "/":

Result = iValue1 / iValue2;

break;

}

return Convert.ToString(Result);

}

如何可以減化改寫成:

private string MathCount (string a, string b, string sym)

{

int Result = 0;

int iValue1 = Convert.ToInt32(a);

int iValue2 = Convert.ToInt32(b);

Result = iValue1 sym iValue2; <--------------★★

return Convert.ToString(Result);

}

1 個解答

評分
  • John
    Lv 7
    6 年前
    最佳解答

    using System;

    using System.Data;

    public class Program {

    public static void Main(string[] args) {

    var result = MathCount("1", "2", "-");

    Console.WriteLine(result);

    }

    private static string MathCount(string a, string b, string sym) {

    var expression = a + sym + b;

    DataTable dt = new DataTable();

    var result = dt.Compute(expression, "");

    return result.ToString();

    }

    }

還有問題?馬上發問,尋求解答。