Issue with Relational Operators

I created a code that determines if a triangle can be formed when the user inputs three side lengths.

This is based on the Triangle Inequality Theorem that states that the sum of any two sides of the triangle must be larger than the third side.

When I input 1.1 3.3 4.4: it states that it is NOT a triangle.

BUT, when I input 1.1 2.2 3.3: it states it is a triangle.

What is wrong with the relational operators?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//This program determines if a triangle is formed given three sides.
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    double sideA, sideB, sideC;
    
    cout<<"Enter the lengths of the sides -> ";
    cin>>sideA>>sideB>>sideC;
    
    if (sideA + sideB <= sideC || sideA + sideC <= sideB || sideB + sideC <= sideA)
    {
        cout<<"*** "<<fixed<<setprecision(3)<<sideA<<", "<<sideB<<" and "
        <<sideC<<" do not satisfy the triangle inequality. ***"<< endl;
    }
    else
        cout<<"It's a triangle!";

    return 0;
}
Last edited on
1 - 2 - 3 give me not a triangle, your code works as expected for me
But if you try 1.1 - 2.2 - 3.3, it says it's a triangle when it's not. It's weird.
@rentantude
doubles are only stored to a finite precision. Unlike ints. Comparing doubles for equality - as in both your cases - is fraught with risk. Both your cases are right on the margin of being a triangle (very degenerate in this case; the sides would effectively form a straight line).
@lastchance
What would be a good workaround to this problem?
I want to be able to input numbers with decimals though and not integers.
@rentandude,
I know of no good "work-around", because that is the nature of finite-precision, floating-point arithmetic: you must be aware of its limitations.

Actually, it is a matter of definition whether you regard 1.1, 2.2, 3.3 as a (rather degenerate) triangle or not - it has three sides and the internal angles add up to 180 degrees, the sine and cosine rules both hold, and the area formula is correct, albeit giving area 0.

Best simply not to worry about the "boundary cases".
Topic archived. No new replies allowed.