我构建了一个二进制计算器应用程序,对于数字我有两个变量。 previousNumber 和 numberOnScreen。这个想法是将二进制数转换为十进制数,进行计算并将答案转换回来。
假设我选择的第一个 (previousNumber) 数字是 1010,第二个 (numberOnScreen) 是 10100
var numberOnScreen:Int = 0;
var previousNumber:Int = 0;
var doingMath = false
var operation = 0;
var decimal = 0;
var decimal1 = 0;
var binary:String = ""
var binary1:String = ""
@IBOutlet weak var label: UILabel!
@IBAction func Numbers(_ sender: UIButton) {
if doingMath == true
{
label.text = String(sender.tag-1)
numberOnScreen = Int(label.text!)!
doingMath = false
}
else
{
label.text = label.text! + String(sender.tag-1)
numberOnScreen = Int(label.text!)!
}
}
@IBAction func buttons(_ sender: UIButton) {
if label.text != "" && sender.tag != 6 && sender.tag != 8
{
previousNumber = Int(label.text!)!
binary = "\(previousNumber)"
decimal = Int(binary, radix: 2)!
binary1 = "\(numberOnScreen)"
decimal1 = Int(binary1, radix: 2)!
operation = sender.tag
doingMath = true;
}
else if sender.tag == 8
{
if operation == 3 //adding
{
print(previousNumber, numberOnScreen, decimal, decimal1)
它打印 [ 1010, 10100, 10, 10 }
有什么想法为什么会发生这种情况吗?
最佳答案
当您按下=键时,您需要更新decimal1
的计算。将该代码移动到您正在处理 = 的位置:
@IBAction func buttons(_ sender: UIButton) {
if label.text != "" && sender.tag != 6 && sender.tag != 8
{
previousNumber = Int(label.text!)!
binary = "\(previousNumber)"
decimal = Int(binary, radix: 2)!
operation = sender.tag
doingMath = true;
}
else if sender.tag == 8
{
binary1 = "\(numberOnScreen)"
decimal1 = Int(binary1, radix: 2)!
if operation == 3 //adding
{
print(previousNumber, numberOnScreen, decimal, decimal1)
<小时/>
此外,我建议您删除代码中的魔数(Magic Number)并用常量替换它们。对于您的关键标签,您可以定义如下结构:
struct Key {
static let clear = 6
static let equals = 8
static let plus = 3
}
然后你的代码将显示为:
if label.text != "" && sender.tag != Key.clear && sender.tag != Key.equals {
这更清楚了。
关于swift - 第二个变量采用第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413423/