0

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

练习是编写一个程序,给定二维图形上的两个点,输出一条描述直线(水平或垂直)或其斜率(正或负)的消息。这就是我到目前为止所拥有的。

# 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

如何在puts "The line is vertical!"不获取 ZeroDivisionError 的情况下生成除以零回报的值?

4

4 回答 4

2

全部替换to_ito_f。然后你可以用 测试一条垂直线slope.abs == Float::INFINITY

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

于 2013-10-09T22:10:03.177 回答
0
x == 0 ? puts "The line is vertical!" : y/x
于 2013-10-09T22:05:05.803 回答
0

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

begin
  1/0
rescue ZeroDivisionError => kaboom
  p kaboom
end
于 2013-10-09T22:05:41.873 回答
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
于 2013-10-09T22:06:25.360 回答