我用Swift构建了一个基本的RPN计算器,我需要添加这些函数:正弦,余弦,正切,倒数(1 / x),对数(基数)和放大器。 log(base10)。 以下是我对基本操作的代码:
import Foundation
import UIKit
class CalculatorEngine: NSObject
{
var operandStack = Array<Double>() //array
func updateStackWithValue(value: Double)
{ self.operandStack.append(value) }
func operate(operation: String) ->Double
{ switch operation
{
case "×":
if operandStack.count >= 2 {
return self.operandStack.removeLast() * self.operandStack.removeLast()
}
case "÷":
if operandStack.count >= 2 {
return self.operandStack.removeFirst() / self.operandStack.removeLast()
}
case "+":
if operandStack.count >= 2 {
return self.operandStack.removeLast() + self.operandStack.removeLast()
}
case "−":
if operandStack.count >= 2 {
return self.operandStack.removeFirst() - self.operandStack.removeLast()
}
case "√":
if operandStack.count >= 1 {
return sqrt(self.operandStack.removeLast())
}
default:break
}
return 0.0
}
答案 0 :(得分:0)
这是Swift中这些基本功能的实现。我会让你把它放到你的RPN计算器中,因为这是你的任务。
内置的trig功能需要以弧度为单位输入,因此您必须通过乘以pi
并除以180.0
进行转换。
func sine(degrees: Double) -> Double {
return sin(degrees * M_PI / 180)
}
func cosine(degrees: Double) -> Double {
return cos(degrees * M_PI / 180)
}
func tangent(degrees: Double) -> Double {
return tan(degrees * M_PI / 180)
}
func log(n: Double, base: Double) -> Double {
return log(n) / log(base)
}
func reciprocal(n: Double) -> Double {
return 1.0 / n
}
对于日志(基数10),只需使用内置的log10(n: Double) -> Double