Always returning incorrect simple math lua

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

I have a very basic Lua script that asks a math question

math.randomseed(os.time())         print ("Let's play Math")         a = math.random(1,10)         b = math.random(1,10)         io.write("What is " .. a .. " + " .. b .. "?")         answer = io.read()         correct = (a + b)             if (answer == correct) then                 print ("Correct")             else                 print ("Wrong")                 print (correct) --For debug             end

For some reason, I am always getting "incorrect" even when answered correctly. I also print out the correct answer, just to make sure the program is handling the math correctly. Where is my mistake?

回答1:

answer contains a string and so is never equal to a number.

Just add

    answer = tonumber(answer)

after

    answer = io.read()


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!