在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
static void Main(string[] args) { /* * 命题:计算 加 减 乘 除,不含括号 */ var str = "8*8*8-100*2"; //计算乘法 str = Calc(str, '*'); str = Calc(str, '/'); str = Calc(str, '+'); str = Calc(str, '-'); Console.WriteLine(str); Console.Read(); } private static string Calc(string exp,char sign) { var r = new Regex(string.Format(@"(\d+)\{0}(\d+)", sign)); var exps = r.Matches(exp); if (exps.Count == 0) return exp; exp = exps.Cast<Match>().Aggregate(exp, (current, p) => current.Replace(p.ToString(), Operate(p.ToString(), sign).ToString())); exp = Calc(exp, sign); return exp; } private static double Operate(string exp,char sign) { var arr = exp.Split(sign); double result = 0; var numA = NumberHelper.FormatDouble(arr[0]); var numB = NumberHelper.FormatDouble(arr[1]); switch (sign) { case '+': result = numA + numB; break; case '-': result = numA - numB; break; case '*': result = numA * numB; break; case '/': result = numB != 0 ? numA/numB : 0; break; } return result; }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论