How to calculates the distance between two decimal numbers (absolute difference) in Ruby

1 Answer

0 votes
# Function that returns the distance between two decimal numbers
def distance_between(a, b)
  # The distance is the absolute value of the difference
  (a - b).abs
end

# Test values
x1 = 100.0
y1 = 45.0

x2 = 100.0
y2 = -15.0

x3 = -100.0
y3 = -125.0

x4 = -600.0
y4 = 100.0

# Print results
puts "Distance between #{x1} and #{y1} = #{distance_between(x1, y1)}"
puts "Distance between #{x2} and #{y2} = #{distance_between(x2, y2)}"
puts "Distance between #{x3} and #{y3} = #{distance_between(x3, y3)}"
puts "Distance between #{x4} and #{y4} = #{distance_between(x4, y4)}"


=begin
run:

Distance between 100.0 and 45.0 = 55.0
Distance between 100.0 and -15.0 = 115.0
Distance between -100.0 and -125.0 = 25.0
Distance between -600.0 and 100.0 = 700.0

=end

 



answered Jun 28 by avibootz

Related questions

...