Rescue Math :: Domain Error

时间:2015-11-24 14:00:12

标签: ruby

我有这种方法可以找到三边形的三角形角度。我想要救援Math::DomainError并打印0代替:

def triangle_type (a, b, c)
  p first=Math.acos((b**2+c**2-a**2) / (2.0*b*c)) * (180 / Math::PI)
  p second=Math.acos((c**2+a**2-b**2) / (2.0*c*a)) * (180 / Math::PI)
  p third=180-(first+second)
end
triangle_type(7,3,2) will produce `Numerical argument is out of domain - "acos" (Math::DomainError)`

1 个答案:

答案 0 :(得分:1)

def triangle_type (a, b, c)
  begin
    p first=Math.acos((b**2+c**2-a**2) / (2.0*b*c)) * (180 / Math::PI)
    p second=Math.acos((c**2+a**2-b**2) / (2.0*c*a)) * (180 / Math::PI)
    p third=180-(first+second)
  rescue Math::DomainError => e  
    puts 0
  end
end

triangle_type(7, 3, 2)