# 使用swift实现计算器功能

```//
//  ViewController.swift
//  Calculator
//
//  Created by CQUPT-ZHX on 2019/4/27.
//

import UIKit
import Darwin

class ViewController: UIViewController {

var Priority = ["+","-","*","÷","="]
var isEq:Bool = false//判断是否输入等于号
var isMinus:Bool = false//判断是否负数
var isControl:Bool = false//判断是否输入操作符
var input:Double = 0.0//存储输入数字
var lastRes:Double = 0.0//存储过度数字
var res:Double = 0.0//存储a答案
var fh:Int = 0//符号tag
var math:Int = 0//运算符tag

@IBOutlet weak var resultsum: UILabel!
}

@IBAction func takesum(_ sender: UIButton) {
//取数字
if isMinus {//取负数后下次显示区清零
resultsum.text = "0"
}
if isControl{//输入运算符后下次显示区清零
resultsum.text = "0"
}
if(resultsum.text! != "0"){
resultsum.text! += String(sender.tag)
}else{
resultsum.text! = String(sender.tag)
}
input = (resultsum.text! as NSString).doubleValue
//获得数字并存储
isEq = false
isMinus = false
isControl = false
}
@IBAction func touchPoint(_ sender: UIButton) {
resultsum.text! += "."
//加入小数点
}
@IBAction func touchMinus(_ sender: UIButton) {
//负数操作
if (res == 0){
equal(sender)
res = -input
} else{
res = -res
}
resultsum.text = String(res)
isMinus = true
}
@IBAction func equal(_ sender: UIButton) {
//等号运算
switch(fh) {
case 1:
res = lastRes + input
case 2:
res = lastRes - input
case 3:
res = lastRes * input
case 4:
res = lastRes / input

default:
break
}
resultsum.text! = "\(res)"
lastRes = res
isEq = true
isControl = true
}
@IBAction func backC(_ sender: UIButton) {
//删除上一个字符
if resultsum.text?.count == 1 {
resultsum.text = "0"
}
else if (resultsum.text! as NSString).doubleValue != 0 {
resultsum.text?.removeLast()
}
input = (resultsum.text! as NSString).doubleValue
}

@IBAction func getsign(_ sender: UIButton) {
//输入运算符
if sender.tag < 5 {
resultsum.text! = Priority[sender.tag - 1]
if isEq {
lastRes = res
}
else {
lastRes = input
}
}
fh = sender.tag
isControl = true
}

@IBAction func touchClean(_ sender: UIButton) {
//清空所有储存
res = 0
lastRes = 0
input = 0
resultsum.text = "0"
isControl = false
}

@IBAction func touchMath(_ sender: UIButton) {
//便捷运算
math = sender.tag
if(res == 0){
res = input
}
switch(math){
case 7:
res = res * 3.14
case 8:
res = res * res
case 9:
res = sin(res)
case 10:
res = cos(res)
default:
break
}
resultsum.text! = "\(res)"
lastRes = res
isEq = true

}

}```