dluffy19
dluffy19

Reputation: 13

Given three edges 1.1, 2.2, 3.3, determine if they can form a triangle using language C, but there's a strange problem

I wrote code of determining if three edges (input) can form a triangle, but when the input is "1.1 2.2 3.3", there's a problem. Here's my code:

#include <stdio.h>
#include <math.h>

int main() {
    float a, b, c;
    float s, area;
    scanf("%f %f %f", &a, &b, &c);
    if (a > 0 && b > 0 && c > 0) {
        if (a + b > c && b + c > a && a + c > b) {
            s = (a + b + c) / 2;
            area = sqrt(s * (s - a) * (s - b) * (s - c));
            printf("%f", area);
        } else
            printf("error input");
    } else {
        printf("error input");
    }
}

When I enter "1.1 2.2 3.3", the output is "0.001380", but it's supposed to be "error input" because 1.1+2.2==3.3. Besides, when I enter other floats like "2.2 3.3 5.5", the output is "error input". Could someone please explain why?

Upvotes: 1

Views: 206

Answers (1)

CodingLab
CodingLab

Reputation: 1519

If you run debugger, you can see a+b==3.30000019 and c==3.29999995 so it's limited precision problem.

You can avoid this by using double type or use epsilon like below

#include <stdio.h>
#include <math.h>

int main() {
    float a, b, c;
    float s, area;
    scanf("%f %f %f", &a, &b, &c);
    if (a > 0 && b > 0 && c > 0) {
        float eps = 1e-5;
        if (fabsf(a + b - c) < eps || fabsf(b + c - a) < eps || fabsf(a + c - b) < eps) {
            printf("error input");
        }
        else {
            s = (a + b + c) / 2;
            area = sqrt(s * (s - a) * (s - b) * (s - c));
            printf("%f", area);
        }
    }
    else {
        printf("error input");
    }
}

Upvotes: 1

Related Questions