如何使计算器以十进制形式计算

时间:2015-03-22 00:50:34

标签: ios swift calculator

这是我的计算器代码,它运行正常!

import UIKit

class ViewController: UIViewController {

var number1 = 0
var number2 = 0
var operation = 0

@IBOutlet var screen: UILabel!


@IBAction func Onebutton(sender: AnyObject) {
    addNumber(1)
}

@IBAction func Twobutton(sender: AnyObject) {
    addNumber(2)
}

@IBAction func Threebutton(sender: AnyObject) {
    addNumber(3)
}

@IBAction func Fourbutton(sender: AnyObject) {
    addNumber(4)
}

@IBAction func Fivebutton(sender: AnyObject) {
    addNumber(5)
}

@IBAction func Sixbutton(sender: AnyObject) {
    addNumber(6)
}

@IBAction func Sevenbutton(sender: AnyObject) {
    addNumber(7)
}

@IBAction func Eightbutton(sender: AnyObject) {
    addNumber(8)
}

@IBAction func Ninebutton(sender: AnyObject) {
    addNumber(9)
}

@IBAction func Zerobutton(sender: AnyObject) {
    addNumber(0)
}

@IBAction func Multiplybutton(sender: AnyObject) {
    operation = 1
}

@IBAction func Dividebutton(sender: AnyObject) {
    operation = 2
}

@IBAction func Addbutton(sender: AnyObject) {
    operation = 3
}

@IBAction func Subtractbutton(sender: AnyObject) {
    operation = 4
}

@IBAction func Equalsbutton(sender: AnyObject) {
    switch operation{
    case 1: screen.text = String (number1*number2)
    case 2: screen.text = String (number1/number2)
    case 3: screen.text = String (number1+number2)
    case 4: screen.text = String (number1-number2)
    default: println()
    }
}


@IBAction func clearbutton(sender: AnyObject) {
    number1 = 0
    number2 = 0
    operation = 0
    screen.text = "0"
}

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.
}

func addNumber (pushButton : Int){
    if operation == 0 {
        number1 = number1*10+pushButton
        screen.text = String (number1)
    } else {
        number2 = number2*10+pushButton
        screen.text = String (number2)
    }
}

}

但我想让计算器以十进制形式计算,而不是四舍五入到最接近的数字。

1 个答案:

答案 0 :(得分:2)

使用浮动。

var number: Float = 0
number = number + 0.1
println(number)
//0.1 should be printed.

您目前基本上是在说:

var number: Int = 0

这几乎是计算机读取它的方式; number是一个整数。为了使数字可以是小数(浮点数),你必须说:

var number: Float = 0