开发者

Ruby -If-Else Statement (Triangle Test)

开发者 https://www.devze.com 2023-03-21 04:56 出处:网络
The question is Crea开发者_高级运维te a function that takes three numbers as input and returns true or false depending on whether those three numbers can form a triangle. Three numbers can form a tria

The question is Crea开发者_高级运维te a function that takes three numbers as input and returns true or false depending on whether those three numbers can form a triangle. Three numbers can form a triangle if the sum of any two sides is greater than the third side.

my answer is:

def is_triangle(a,b,c)

  if a+b > c
    return true
  elsif a+c>b
    return true
  elsif b+c>a
    return true
  else
    return false
  end
end

the thing is: my supposed false return keeps returning true. please help!


This logic should work for finding your triangle

def is_triangle?(a,b,c)
  sorted = [a,b,c].sort
  greatest_side = sorted.pop
  greatest_side < sorted.sum
end


Yet another approach:

def is_triangle?(a,b,c)
  [a,b,c].max < [a,b,c].sum/2.0
end

Or for Ruby outside of Rails:

def is_triangle?(a,b,c)
  [a,b,c].max < [a,b,c].inject(:+)/2.0
end


Your problem is that unless all 3 numbers are 0 one of your ifs will always be true. What you want is something more like

def is_triangle(a,b,c)
  a + b > c && a + c > b && b + c > a
end
is_triangle(3,6,8) #=> true
is_triangle(3,6,80) #=> false


Nothing you pass into this is going to return false. Your method is wrong.

You can tell if three sides make a triangle by finding the longest side and then adding the remaining two sides. If they are greater than the longest side, then the sides can make a traingle.


I suggest if you are sure your logic is correct change the method to

def is_triangle?(a, b, c)
   a+b > c or b+c > a or c+a > b
end

But according to me it is not so the method should be

def is_triangle?(a, b, c)
   a+b>c and b+c>a and c+a>b
end

Some points to note about ruby conventions:

  1. Method which returns boolean ends with '?'
  2. A ruby method returns the last evaluated expression, so writing return is redundant here.


puts " enter a, b and c values"

a=gets.to_i
b=gets.to_i
c=gets.to_i

  if a+b > c    
   print true
  elsif a+c>b  
    print true
  elsif b+c>a
    print true
  else
   print false
 end

you can also use this code too.. this is much easy


This is also a solution to this problem :

if 2*[a,b,c].max < a + b + c
    true
else
    false
end

There are a variety of different inequalities theoretically possible:

http://en.wikipedia.org/wiki/Triangle_inequality

0

精彩评论

暂无评论...
验证码 换一张
取 消