-1

I wrote a program in "dev-c++" about discussing about a point. We want to know that it is in or out a triangle. Why doesn't my program work correctly? What should I do? This is my program:

#include <iostream>
#include <math.h>
int main()
{
    int n,a,b,c,d;
    int x[n];
    int y[n];
    n=1;
    while (n<=4)
    {
        std:: cin >> x[n];
        std:: cin >> y[n];
        n=n+1;
    }
    a= fabs((1/2)*((x[1]*(y[2]-y[3]))+(x[2]*(y[3]-y[1]))+(x[3]*(y[1]-y[2]))));
    b= fabs((1/2)*((x[1]*(y[2]-y[4]))+(x[2]*(y[4]-y[1]))+(x[4]*(y[1]-y[2]))));
    c= fabs((1/2)*((x[1]*(y[3]-y[4]))+(x[3]*(y[4]-y[1]))+(x[4]*(y[1]-y[3]))));
    d= fabs((1/2)*((x[2]*(y[3]-y[4]))+(x[3]*(y[4]-y[2]))+(x[4]*(y[2]-y[3]))));
        if ((b+c+d)!= a)
    {
        std:: cout<< "out of triangle\n";
    }
    if (b+c+d==a)
    {
        std:: cout <<"in triangle\n";
    }
}
user1118321
  • 25,567
  • 4
  • 55
  • 86

1 Answers1

1

The input of this program consists of integer coordinates only, but to check if a point lies inside a triangle this method needs to know the area of triangles. The area of a triangle is

A = width * height / 2

and because of that final division it may return a floating point number. Thus, the intermediate variables a, b, c, d need to be at least float.

As long as all of the constants and variables at the right hand side of an = are integer, C calculates the result as an integer as well. Only at the very last step the result gets converted to the destination type. Thus,

double x = 2*3/4;

will be calculated as 2*3/4 using integers and resulting in 6/4 -> 1, and only then converted to a double value: 1.000. Forcing the intermediates to a float type fixes it:

double x = 2.0*3/4;

and then x = 1.5.


Be aware that when using floating point numbers, you could have run into accuracy problems with the final comparison

if (b+c+d==a)
  ...

Fortunately, this will not be a problem with your divisions by 2. The decimal value 0.5 can be represented exactly in float and double formats, as long as the 'whole' part does not exceed the number of available digits. But it's a good thing to keep in mind nevertheless.

Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100