Question

The program is set to calculate the area of a triangle. Triangle sides (a,b,c) are an input. The code works fine only with certian numbers and not with others. E.g.

when a,b and c are respectively: 2,3,4 the code is OK. 2,3,5 the output in 0.00 which is wrong. 2,3,6 the program prints a math domain error

def main():
    print "Program calculates the area of a triangle."
    print
    a, b, c = input("Enter triangle's sides length: ")
    s = (a+b+c) / 2.0
    area = sqrt(s*(s-a)*(s-b)*(s-c))
    print "The area is %.2f" % area

main()

can you see what's wrong?

Was it helpful?

Solution 2

Your code seems legit, let's look at your test cases in math:

Case 1:

a=2; b=3; c=5;

s=(2+3+5)/2.0
 = 5.00

And you have area = sqrt(s*(s-a)(s-b)(s-c))

See there is (s-c) in the formula, which turn out to be (5.00 - 5) = 0 In this case area = 0.00, which is correct.

Case 2:

a=2; b=3; c=6;

s=(2+3+6)/2.0
 = 5.50

in terms of (s-c), you have (5.50 - 6) = -0.5

sqrt of a negative number gives you the "math domain error"

The above results implies that these numbers cannot form legit triangles. There is nothing wrong with your code or the formula. However, make sure your test cases are legit before you test your code next time.

I hope it helps =]

OTHER TIPS

The formula is working; it's your expectations which are a little off.

2,3,5 the output in 0.00 which is wrong.

Really? Could you draw a triangle with side lengths of of 2, 3, and 5, then? :^) The only possibility is a degenerate triangle -- a line (a 2-inch segment joined to a 3-inch segment), which obviously has zero area.

Not every combination of three numbers works as a triangle. You need to have a+b>c, b+c>a, and c+a>b. For (2,3,6), you have

3+6 > 2 and 6+2 > 3, but 2+3 < 6, so there's no such triangle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top