Operators/IF statement not working as expected with negative numbers


#1

This is my code:

puts "Enter a number: "
a = gets.chomp
puts "Enter a second number: "
b = gets.chomp

if a > b
  puts "The first number is bigger!"
elsif
  a < b
  puts "The second number is bigger!"
else
  puts "The two numbers are equal!"
end

When a == -1 and b == -2 it returns a is greater than b.

Is there a problem with my code?

Thanks


#2

no, -1 is greater then -2.


#3

Apologises; I miss-typed. It’s actually return that b is greater than a

The below is an example of output I am seeing:

Enter a number: 
-1
Enter a second number: 
-2
The second number is bigger!

I very well may just be confusing myself.


#4

a and b variable are of type string, string comparing numbers gives unexpected behavior.


#5

Ah I see. I guess this will be covered in a later lesson/I will have to research it.

Thank you for your help and your quick replies.


#6

just convert a and b to integers, then all should work fine


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.