0

「Computer Science Programming Basics in Ruby」やその他の情報源を使用して Ruby を独学しようとしています。質問に行き詰まっていますが、この本には解決策がありません。

課題は、2D グラフ上の 2 つの点を指定すると、線 (水平または垂直) またはその勾配 (正または負) を説明するメッセージを出力するプログラムを作成することです。これは私がこれまでに持っているものです。

# 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_iすべてを に置き換えますto_f。次に、 で垂直線をテストできますslope.abs == Float::INFINITY

完全を期すために、slope.nan?出力する最初のテストとしてテストを含めますThose are not two distinct points!。これにより、同じポイントに 2 回入る場合がカバーされます。

于 2013-10-09T22:10:03.177 に答える
0

Rubyでゼロ除算操作をレスキューすることもできます

begin
  1/0
rescue ZeroDivisionError => kaboom
  p kaboom
end
于 2013-10-09T22:05:41.873 に答える
0

これを行う 1 つの方法は、次のようなレスキューで方程式に従うことです。

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 に答える
0
x == 0 ? puts "The line is vertical!" : y/x
于 2013-10-09T22:05:05.803 に答える