用Xcode简单实现了计算器的功能。
平时没有写代码(做设计),所以错漏百出,代码质量不高。
另外很多东西只是知其然,不知其所以然。
一开始觉得很简单,可是后来,比我想象的复杂很多,很多逻辑没想清楚。还有就是对计算器的产品逻辑不了解,一些非正常的操作不熟悉。
总结
写程序前必须做好准备,理清思路,逻辑清晰,预想各种特殊情况。
体验已有的产品,熟悉正常的产品逻辑,避免不合常理。
swift对变量的数据类型要求很严格。
switch语句处理optional,“ ! ”和“ ? ”没有理解,optional拆包等等。
如果要改进程序,还需要增加更多的变量,识别是否键入第二操作数,是否键入小数点,把显示和计算的数据类型分开,添加错误处理。
基本逻辑
键入按钮分为五种:数字、符号、小数点、等号、清零
- 当前键入的数字永远保存到后一个操作数里,当键入符号和等号时,后一个操作数推入前一个操作数,新键入的数字依然保存在后一个操作数里。
- 通过按钮的文字,获取当前点击的操作。
- 当小数点激活时,每次键入数字小数点操作数乘以0.1,来改变当前小数点位置。
- 键入符号,后一个操作数推入前一个操作数里,后一个操作数清零。
- 清零则全部清除,包括所有的操作数。
当前程序问题
- 连续点击等号,无法继续计算
- 没有错误处理,比如除数不能为零
- 整数的计算,数字带了.0
- 分不清零和空(大问题,汗)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var xianshi: UILabel!
var qianyige:Double = 0
var houyige:Double = 0
var jieguo:Double = 0
var point:Double = 0.0
var fuhao:String?
@IBAction func shuzi(sender: AnyObject) {
if (point == 0.0) {
switch sender.currentTitle! {
case "1"?:
houyige = 1 + houyige * 10
case "2"?:
houyige = 2 + houyige * 10
case "3"?:
houyige = 3 + houyige * 10
case "4"?:
houyige = 4 + houyige * 10
case "5"?:
houyige = 5 + houyige * 10
case "6"?:
houyige = 6 + houyige * 10
case "7"?:
houyige = 7 + houyige * 10
case "8"?:
houyige = 8 + houyige * 10
case "9"?:
houyige = 9 + houyige * 10
case "0"?:
houyige = houyige * 10
default:
print("shuzi")
}
} else if (point != 0.0) {
switch sender.currentTitle! {
case "1"?:
houyige = (point * 1) + houyige
case "2"?:
houyige = (point * 2) + houyige
case "3"?:
houyige = (point * 3) + houyige
case "4"?:
houyige = (point * 4) + houyige
case "5"?:
houyige = (point * 5) + houyige
case "6"?:
houyige = (point * 6) + houyige
case "7"?:
houyige = (point * 6) + houyige
case "8"?:
houyige = (point * 6) + houyige
case "9"?:
houyige = (point * 6) + houyige
case "0"?:
point = point * 0.1
default:
print("shuzi")
}
point = point * 0.1
}
xianshi.text = String(houyige)
}
@IBAction func add(sender: AnyObject) {
if houyige != 0 {
qianyige = houyige
houyige = 0
}
point = 0.0
fuhao = sender.currentTitle
}
@IBAction func clear(sender: AnyObject) {
qianyige = 0
houyige = 0
jieguo = 0
point = 0.0
xianshi.text = "0"
}
@IBAction func output(sender: AnyObject) {
if (qianyige != 0) && (houyige != 0) && (fuhao != "") {
switch fuhao! {
case "加":
jieguo = qianyige + houyige
case "减":
jieguo = qianyige - houyige
case "乘":
jieguo = qianyige * houyige
case "除":
jieguo = qianyige / houyige
default:
print("output")
}
xianshi.text = String(jieguo)
fuhao = ""
houyige = 0
qianyige = jieguo
point = 0.0
}
}
@IBAction func point(sender: AnyObject) {
if point == 0.0 {
point = 0.1
}
}
}