【问题标题】:What is wrong with my code? 5 + 5 will give me 55 instead of 10我的代码有什么问题? 5 + 5 会给我 55 而不是 10
【发布时间】:2015-03-19 09:01:02
【问题描述】:
@IBAction func calcAns(sender: UIButton) {

   result = firstNumber.text + secondNumber.text
   outputLabel.text = "\(result)"


}

我的代码有什么问题?例如 5 + 5 会给我 55 而不是 10。有人可以指出我的错误吗?

【问题讨论】:

  • 您的变量被视为字符串而不是 int,您需要将其转换为 int(或强制转换)
  • 5 + 5 = 10,但"5" + "5" = "55"
  • 不要忘记在下面投票和/或接受答案,以表达对您所获得帮助的感谢。谢谢!

标签: swift addition


【解决方案1】:

您正在将一个字符串添加到另一个字符串:

firstNumber.text + secondNumber.text

如果firstNumber.text 是“Hello”并且secondNumber.text 是“World”,则结果将是“HelloWorld”。实际上,您将“5”和“5”连接起来得到“55”。

解决方案是将这些字符串转换为数字值,然后再将它们相加。

【讨论】:

    【解决方案2】:

    需要将字符串变量转换为int:

    @IBAction func calcAns(sender: UIButton) {
    
       result = firstNumber.text.toInt() + secondNumber.text.toInt()
       outputLabel.text = "\(result)"
    
    
    }
    

    【讨论】:

      【解决方案3】:

      在 Swift 中,字符串上的 + 是连接而不是加法。 text 属性是字符串而不是数字。

      要将其转换为数字,请尝试:

      if let first = firstNumber.text.toInt(),
             second = secondNumber.text.toInt() {
      
          outputLabel.text = toString(first + second)
      
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        相关资源
        最近更新 更多