using System; using System.Linq;
namespace Calculator { class Program { static void Main(string[] args) { for (int i = 0; i < 3; i++) { string inputStr = Console.ReadLine(); CalcOnline(inputStr); }
} static CalcInfo[] configs = new CalcInfo[] { new CalcInfo("+",(a,b)=>a+b), new CalcInfo("-",(a,b)=>a-b), new CalcInfo("*",(a,b)=>a*b), new CalcInfo("/",(a,b)=>a/b), }; private static void CalcOnline(string inputStr) { int index = -1; Func<float, float, float> func = null; for (int i = 0; i < configs.Length; i++) { var item = configs[i]; index = inputStr.IndexOf(item.tag); if (index != -1) { func = item.func; break; }
} if (index == -1) { Console.WriteLine("只支持+-*/"); return; } CalcResult(inputStr, func, index); }
private static void CalcResult(string inputStr, Func<float, float, float> func, int index) { string num1Str = inputStr.Substring(0, index); int strLen = inputStr.Count(); Console.WriteLine($"strLen:{strLen},index:{index}"); string num2Str = inputStr.Substring(index+1,strLen-index-1); float num1 = float.Parse(num1Str); float num2 = float.Parse(num2Str); Console.WriteLine($"num1:{num1}, num2:{num2}"); float result = func(num1, num2); Console.WriteLine($"{inputStr}的计算结果:{result}"); } } public class CalcInfo { public string tag; public Func<float, float, float> func; public CalcInfo(string tag, Func<float, float, float> func) { this.tag = tag; this.func = func; } }
}
|