Swift无UI控制台简易计算器返回nil问题求助
问题原因
你代码里的Double(response)只能将纯数字字符串(比如"3"、"4.5")转换为Double类型值,但输入的"1+2"是包含运算符的数学表达式,这个初始化器无法解析这类字符串,所以返回nil。
解决方案
Swift标准库没有直接解析数学表达式的API,但可以用Foundation框架里的NSExpression来实现表达式计算,以下是修改后的代码:
import Foundation print("Please enter a mathematical equation\n(ex. 1+2, 1-2, 1*2, 1/2, (1+2)-3, 1^2)\n") if let response = readLine() { print("Your math equation is:", response) // 处理乘方符号^,NSExpression用**表示乘方 let formattedExpression = response.replacingOccurrences(of: "^", with: "**") if let expression = NSExpression(format: formattedExpression), let result = expression.expressionValue(with: nil, context: nil) as? Double { print("The answer is:", result) } else { print("Invalid equation, please enter a valid mathematical expression.") } }
代码说明
- 导入
Foundation框架才能使用NSExpression - 把输入里的
^替换成**,因为NSExpression用**表示乘方运算 NSExpression(format:)会把字符串解析成表达式,expressionValue(with:context:)执行计算并返回结果,再转成Double类型- 增加了错误处理,输入无效表达式时会提示用户
内容的提问来源于stack exchange,提问作者oprumo _
相关产品推荐
相关产品推荐

