简体   繁体   中英

Why is my Lua if-else not working properly?

print("Type a number:")
firstNum = io.read()
print("Type another number:")
secondNum = io.read()
print("First: " .. firstNum .. "\nSecond: " .. secondNum)
if firstNum > secondNum then
  print("first is bigger than second")
elseif firstNum < secondNum then
  print("first is less than second")
else
  print("first is equal to second")
end

Input:
firstNum = 5
secondNum = 15
Output:
first is bigger than second
Why is that happening?

firstNum and secondNum are strings, and "5" lexicographically comes after "15" because it starts by comparing the first characters only : '5' > '1' .

You need to convert them to numbers before comparing.

print("Type a number:")
firstNum = tonumber(io.read())
print("Type another number:")
secondNum = tonumber(io.read())
if firstNum > secondNum then
  print("first is bigger than second")
elseif firstNum < secondNum then
  print("first is less than second")
else
  print("first is equal to second")
end

This prints the expected first is less than second .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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