RPN 计算器 (Swift xcode) - 正弦、余弦、正切、倒数 (1/x)、对数(基数)函数

RPN calculator (Swift xcode) - sine, cosine, tangent, reciprocal (1/x), log (base) functions

我已经用 Swift 构建了一个基本的 RPN 计算器,我需要添加这些函数:正弦、余弦、正切、倒数 (1/x)、对数 (base) 和对数 (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
    }

下面是Swift中那些基本功能的实现。我会让你把它输入你的 RPN 计算器,因为那是你的作业。

内置三角函数需要以弧度为单位输入,所以你必须乘以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
}

对于 log(base 10) 只需使用内置 log10(n: Double) -> Double