Ruby程序中的ZeroDivisionError

时间:2013-10-09 22:00:43

标签: ruby

我正在尝试使用“Ruby中的计算机科学编程基础”和其他来源教自己Ruby。我被困在一个问题上,本书没有提供解决方案。

练习是编写一个程序,在2d图形上给出两个点,输出描述直线(水平或垂直)或斜率(正或负)的消息。这是我到目前为止所做的。

# Get the first point from a user
puts "Please enter Point A's X value."
x_1 = gets.to_i
puts "Please enter Point A's Y value."
y_1 = gets.to_i

# Get the second point from a user
puts "Please enter Point B's X value."
x_2 = gets.to_i
puts "Please enter Point B's Y value."
y_2 = gets.to_i

slope = ((y_1-y_2) / (x_1-x_2))


#Check to see if the line is vertical or horizontal and the slope is +ve or -ve
case 
when (slope == 0) then
puts "The line is horizontal."
when (slope > 0) then
puts "The slope is positive."
when (slope < 0) then
puts "The slope is negative."
when (x_1-x_2 == 0) then
puts "The line is vertical."
end

如何在不获取ZeroDivisionError的情况下创建一个除以零返回puts "The line is vertical!"的值?

4 个答案:

答案 0 :(得分:2)

将所有to_i替换为to_f。然后,您可以使用slope.abs == Float::INFINITY测试垂直线。

为了完整性,请将测试slope.nan?作为输出Those are not two distinct points!的第一个测试。这将涵盖他们两次进入同一点时的情况。

答案 1 :(得分:0)

x == 0 ? puts "The line is vertical!" : y/x

答案 2 :(得分:0)

您还可以在ruby中拯救除以零操作

begin
  1/0
rescue ZeroDivisionError => kaboom
  p kaboom
end

答案 3 :(得分:0)

执行此操作的一种方法是通过救援来遵循您的等式,例如

2/0 # this throws an error

2/0 rescue "This line is vertical" # this prints the rescue

2/2 rescue "This line is vertical" # this prints 1