简体   繁体   English

将字符串转换为int以检查答案

[英]Converting string to int for check answer

For my math question app I have two random numbers generated then I have 4 buttons as answers. 对于我的数学问题应用程序,我生成了两个随机数,然后有4个按钮作为答案。 I want to check the answer if the user pushes the right button but it seems not to work. 我想检查答案,如果用户按右键,但似乎不起作用。

num1 and num2 are the labels which the random numbers are generated in so technically num1和num2是从技术上讲会生成随机数的标签

num1.text = "(randomnum1)" num1.text =“(randomnum1)”

and num2.text = "(randomnum2)" Thanks. 和num2.text =“(randomnum2)”谢谢。

I have the following code under button1 IBaction 我在button1 IBaction下有以下代码

    var sum = (num1) + (num2)
    if btn1.titleLabel = (sum){
            check.text = "right"            
    }

you have two options: 您有两种选择:

if btn1.titleLabel.toInt()! == sum

or 要么

if btn1.titleLabel == String(sum)

consider the difference between = (assign) and == (is equal) 考虑= (分配)和== (等于)之间的差异

to assign a number to a label use 给标签使用分配一个数字

num1.text = "\(randomnum1)"

I recommend to use backing Int variables like randomnum1 to hold the random numbers which can used for the math for example 我建议使用支持Int变量(例如randomnum1来保存可用于数学的随机数,例如

var randomnum1 = 0, randomnum2 = 0 // instance variables of the class

randomnum1 = randomFuntion()
randomnum2 = randomFuntion()

num1.text = String(randomnum1)
num2.text = String(randomnum2)

now the labels contain the string values of the random numbers, but you can do the math with the associated variables. 现在,标签包含随机数的字符串值,但是您可以使用关联的变量进行数学运算。

var sum = randomnum1 + randomnum2

after that you can check the result as mentioned above 之后,您可以如上所述检查结果

if btn1.titleLabel == String(sum) {
   check.text = "right"   
}

Maybe you should do some convert before you add num1 and num2. 也许您应该在添加num1和num2之前进行一些转换。 (convert strings to integers before adding them up, also, you should convert string to integer fisrt when comparing sum and btn.titleLabel) (在将字符串相加之前将字符串转换为整数,并且,在比较sum和btn.titleLabel时,也应将字符串转换为整数fisrt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM