C#单行输入控制台计算器开发求助:支持多运算符连续计算
控制台计算器扩展开发求助
我正在开发一款控制台小型计算器,要求用户在控制台单行输入运算表达式,例如输入"88+12*7/2"需按照从左到右依次计算的逻辑(即转换为((88+12)*7)/2)并输出结果。目前已完成部分代码,但仅支持两个数字的运算,需要协助完善代码。
已实现的代码
static string Input_User() { string Input_User = Console.ReadLine(); return Input_User; } static void ShowMessage() { Console.WriteLine("Enter your numbers with operation like: 7*7"); } ShowMessage(); string input_string = Input_User(); int result = PerformCalculation(InputToList(input_string)); Console.WriteLine($"{input_string}={result}"); static string[] InputToList(string input) { string number1 = ""; string number2 = ""; string Oprt = ""; string[] Arithmetic = new string[3]; int n = 0; foreach (char charecter in input) { int num; bool isNumerical = int.TryParse(charecter.ToString(), out num); n += 1; if (isNumerical) { number1 += num; } else { Oprt = charecter.ToString(); Arithmetic[0] = number1; Arithmetic[1] = Oprt; for (int i = n; i <= input.Length - 1; i++) { number2 += input[i]; } Arithmetic[2] = number2; } } return Arithmetic; } static int PerformCalculation(string[] Input) { int result = 0; switch (Input[1]) { case "+": result = Int32.Parse(Input[0]) + Int32.Parse(Input[2]); break; case "-": result = Int32.Parse(Input[0]) - Int32.Parse(Input[2]); break; case "*": result = Int32.Parse(Input[0]) * Int32.Parse(Input[2]); break; case "/": result = Int32.Parse(Input[0]) / Int32.Parse(Input[2]); break; } return result; }
完善方案
原代码仅能处理两个数字的表达式,要支持多数字连续运算,需要修改核心逻辑:拆分表达式为数字和运算符列表,再按左到右顺序逐步计算。
1. 重构表达式拆分方法
将原InputToList改为拆分所有数字和运算符,分别存入列表,方便迭代计算:
static (List<int> numbers, List<char> operators) ParseExpression(string input) { var numbers = new List<int>(); var operators = new List<char>(); string currentNumber = ""; foreach (char c in input) { if (char.IsDigit(c)) { currentNumber += c; } else if ("+-*/".Contains(c)) { if (int.TryParse(currentNumber, out int num)) { numbers.Add(num); currentNumber = ""; operators.Add(c); } else { throw new ArgumentException("无效的数字格式"); } } else { throw new ArgumentException($"不支持的字符: {c}"); } } if (int.TryParse(currentNumber, out int lastNum)) { numbers.Add(lastNum); } else { throw new ArgumentException("表达式结尾无效"); } return (numbers, operators); }
2. 重构计算方法
按左到右顺序,每次取前两个数字和第一个运算符计算,用结果替换原位置,直到只剩一个结果:
static int PerformCalculation((List<int> numbers, List<char> operators) expression) { var nums = new List<int>(expression.numbers); var ops = new List<char>(expression.operators); while (nums.Count > 1) { int num1 = nums[0]; int num2 = nums[1]; char op = ops[0]; int tempResult = op switch { '+' => num1 + num2, '-' => num1 - num2, '*' => num1 * num2, '/' => num2 == 0 ? throw new DivideByZeroException("不能除以零") : num1 / num2, _ => throw new ArgumentException($"不支持的运算符: {op}") }; nums.RemoveRange(0, 2); nums.Insert(0, tempResult); ops.RemoveAt(0); } return nums[0]; }
3. 调整主程序逻辑
更新主代码,调用新方法并添加异常处理:
static void ShowMessage() { Console.WriteLine("Enter your numbers with operation like: 88+12*7/2"); } ShowMessage(); string input_string = Console.ReadLine(); try { var expression = ParseExpression(input_string); int result = PerformCalculation(expression); Console.WriteLine($"{input_string}={result}"); } catch (Exception ex) { Console.WriteLine($"错误: {ex.Message}"); }
完整代码
using System; using System.Collections.Generic; class Calculator { static void Main() { ShowMessage(); string input_string = Console.ReadLine(); try { var expression = ParseExpression(input_string); int result = PerformCalculation(expression); Console.WriteLine($"{input_string}={result}"); } catch (Exception ex) { Console.WriteLine($"错误: {ex.Message}"); } } static void ShowMessage() { Console.WriteLine("Enter your numbers with operation like: 88+12*7/2"); } static (List<int> numbers, List<char> operators) ParseExpression(string input) { var numbers = new List<int>(); var operators = new List<char>(); string currentNumber = ""; foreach (char c in input) { if (char.IsDigit(c)) { currentNumber += c; } else if ("+-*/".Contains(c)) { if (int.TryParse(currentNumber, out int num)) { numbers.Add(num); currentNumber = ""; operators.Add(c); } else { throw new ArgumentException("无效的数字格式"); } } else { throw new ArgumentException($"不支持的字符: {c}"); } } if (int.TryParse(currentNumber, out int lastNum)) { numbers.Add(lastNum); } else { throw new ArgumentException("表达式结尾无效"); } return (numbers, operators); } static int PerformCalculation((List<int> numbers, List<char> operators) expression) { var nums = new List<int>(expression.numbers); var ops = new List<char>(expression.operators); while (nums.Count > 1) { int num1 = nums[0]; int num2 = nums[1]; char op = ops[0]; int tempResult = op switch { '+' => num1 + num2, '-' => num1 - num2, '*' => num1 * num2, '/' => num2 == 0 ? throw new DivideByZeroException("不能除以零") : num1 / num2, _ => throw new ArgumentException($"不支持的运算符: {op}") }; nums.RemoveRange(0, 2); nums.Insert(0, tempResult); ops.RemoveAt(0); } return nums[0]; } }
功能说明
- 支持多数字连续运算,严格按左到右顺序计算(如
88+12*7/2会得到350) - 增加异常处理,覆盖无效字符、无效数字、除零错误等场景
- 代码结构更清晰,拆分与计算逻辑分离,便于后续扩展
内容的提问来源于stack exchange,提问作者Slahtalab mohsen
相关产品推荐
相关产品推荐

