This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
bart74's profile picture

simple program that don't work

Started by bart74, 11 June 2013 - 11:40 AM
bart74 #1
Posted 11 June 2013 - 01:40 PM
I'm having issues with this really simple program I made


x=math.random(1,9)
y=math.random(1,9)
write(x.."+"..y.."=")
answer=read()
z=x+y
print(z)
if answer==z then
print("NICE!")
else print("wrong")
end

it's a simple program that ask you the sum of 2 random chosen nubers
the problem is that,whatever the answer I put,it says wrong,even if it's correct,I don't know what is wrong with this code,it should works,but it look like that it can't compair the user answer with "z" wich is the correct answer,I even tried to make it write "z" (that's why there is a "print(z)" on Ln 6) and it still do that even when answer match "z"
I already know that it's possible to make the computer compair a hand-written answer with a variable (like in password programs) but it seems to don't work with random numbers

is it possible to fix it,if yes,how?
thanks
Lyqyd #2
Posted 11 June 2013 - 02:48 PM
Split into new topic.

Change `answer = read()` to `answer = tonumber(read())`. Read always returns a string. Comparing a string and a number is always false, so you must change it to a number first.
bart74 #3
Posted 11 June 2013 - 03:31 PM
Split into new topic.

Change `answer = read()` to `answer = tonumber(read())`. Read always returns a string. Comparing a string and a number is always false, so you must change it to a number first.
it's working,thanks a lot,now I'll be able to do more complex programs
H4X0RZ #4
Posted 11 June 2013 - 03:48 PM
First of all, please use local variables! Global onces are … mad.

To be sure that the input is a number:

local answer = read()
while not tonumber(answer) do
print("please insert a number!")
answer = read()
end
answer = tonumber(answer)
Lyqyd #5
Posted 11 June 2013 - 04:32 PM
Or, y'know,


local answer
repeat
  print("Please enter a number:")
  answer = tonumber(read())
until answer