我有代码:
@IBOutlet weak var summaryLbl: UILabel!
var actualNumber: Double = 0
var previousNumber: Double = 0
var operationMath: Bool = false
var operation = 0
@IBAction func numberPressed(_ sender: UIButton) {
if operationMath == true
{
summaryLbl.text = String(sender.tag)
actualNumber = Double(summaryLbl.text!)!
operationMath = false
}
else
{
if summaryLbl.text == "0" {
summaryLbl.text = ""
}
summaryLbl.text = summaryLbl.text! + String(sender.tag)
actualNumber = Double(summaryLbl.text!)!
}
}
@IBAction func buttons(_ sender: UIButton) {
if summaryLbl.text != "" && sender.tag != 10 && sender.tag != 17
{
previousNumber = Double(summaryLbl.text!)!
if sender.tag == 13
{
summaryLbl.text = "/";
}
else if sender.tag == 14
{
summaryLbl.text = "x";
}
else if sender.tag == 15
{
summaryLbl.text = "-";
}
else if sender.tag == 16
{
summaryLbl.text = "+";
}
operation = sender.tag
operationMath = true;
}
else if sender.tag == 17
{
if operation == 13
{
let summary = rounding(number: previousNumber / actualNumber)
summaryLbl.text = summary
}
else if operation == 14
{
let summary = rounding(number: previousNumber * actualNumber)
summaryLbl.text = summary
}
else if operation == 15
{
let summary = rounding(number: previousNumber - actualNumber)
summaryLbl.text = summary
}
else if operation == 16
{
let summary = rounding(number: previousNumber + actualNumber)
summaryLbl.text = summary
}
else if operation == 11 //TODO: negative numbers
{
let summary = rounding(number: previousNumber + actualNumber)
summaryLbl.text = summary
}
else if operation == 12 //TODO: percentages
{
let summary = rounding(number: (previousNumber * actualNumber) / 100)
summaryLbl.text = summary
}
}
else if sender.tag == 10
{
summaryLbl.text = "0"
previousNumber = 0;
actualNumber = 0;
operation = 0;
}
}
override func viewDidLoad() {
super.viewDidLoad()
summaryLbl.text = "0"
previousNumber = 0;
actualNumber = 0;
operation = 0;
}
func rounding (number: Double) -> String {
let numberAfterRounding = String(number)
return numberAfterRounding
}
我在做一个小型计算器。
我有一个问题:
答案 0 :(得分:1)
问题1的答案
假设结果为3.0,并且您只想显示"3"
而不是"3.0"
,并且对于1.23
,您想显示"1.23"
。首先四舍五入数字,检查四舍五入的数字和结果是否相同。如果它们相同,则将其转换为Int并进行插值。
这是代码。
let result: Double = 3.0
let rounded = result.rounded()
if (result == rounded) { yourLabel.text = "\(Int(result))" }
else { yourLabel.text = "\(result)" }
问题2的答案
Swift具有negate()
功能,可以完全满足您的需求。
var result: Double = 30
result.negate() // it's now -30
result.negate() // it's now 30 again
问题3的答案
我假设当您说百分比(%)时,您是指模量。
快速地,您不能在像3.0 % 1.0
这样的浮点上使用%(模运算符)。而是必须使用truncatingRemainder(dividiedBy:)
函数。
result.truncatingRemainder(dividedBy: 10) // can be any number you like