Problem in calculating the area & centroid of a polygon

Hello readers, this is my official first post on c++ forum. I have a program in the C language that I wrote for my physics class. The problem I have with it is that the program gives me an incorrect numerical value. I should be getting like 2.33208e-05 (checked using IDL) for the Area. But, I am getting 0.15993, -0.052168, and 0.341942. I have three data files that after using gcc -o hmkw1 hmkw1.c I type ./hmwk1 < poly1.dat in my terminal. Here is a copy of my program & any help will be most appreciated.

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

main () {

double x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,Area,CentroidX,CentroidY; /* This is where I define my variables in relation to the poly*.dat files*/

scanf("%lf %lf \n %lf %lf \n %lf %lf \n %lf %lf \n %lf %lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4,&x5,&y5); /*This will read the values of the variables in \
the file*/

Area=(0.5)*((x1*y2-x2*y1)+(x2*y3-x3*y2)+(x3*y4-x4*y3)+(x4*y5-x5*y4)); /*This is the formula that will calculate the area of the polygon.*/

printf("The Area is: %lf \n ", Area); /*This will print out the numerical value for the Area*/

CentroidX=(1/(6*Area))*(((x1+x2)*(x1*y2-x2*y1))+((x2+x3)*(x2*y3-x3*y2))+((x3+x4)*(x3*y4-x4*y3))+((x4+x5)*(x4*y5-x5*y4))); /*This is the formula that will \
calculate the centroid_X of the polygon*/

printf("The CentroidX is: %lf \n", CentroidY); /*This will print out the numerical value for the Centroid_X */

CentroidY=(1/(6*Area))*(((y1+y2)*(x1*y2-x2*y1))+((y2+y3)*(x2*y3-x3*y2))+((y3+y4)*(x3*y4-x4*y3))+((y4+y5)*(x4*y5-x5*y4))); /*This will calculate the centro\
id_Y of the polygon*/

printf("The CentroidY is: %lf \n", CentroidY); /*This will print out the numerical value for the Centroid_Y"*/

}

This is poly1.dat:

0.1921780749668221 0.37518416669349225
0.2106457357350626 0.11390249560734858
0.6675434701321845 0.25979319367958775
0.9937605645223875 0.6298134994674807
0.623641689811437 0.63278901708283

This is poly2.dat:

0.820500869659614 0.3765895866633482
0.7859771510098064 0.3197782322092756
0.5184630032910378 0.14117518556790729
0.005895802840311507 0.28204530735090766
0.5826429791546198 0.5162151728718769

This is poly3.dat:

0.6874979500195675 0.5251513704985208
0.8221939190856469 0.6782315646840115
0.519187316616469 0.9383077996293845
0.45499137296144737 0.985608687984722
0.0019827448898185602 0.323512437112826

Try two things:

First, print out the values of x1-x5 and y1-y5 after you read them to make sure you read them correctly.

Second, try an example that uses only integer values. It is a long story, but floating point arithmetic is prone to roundoff error. See if your program generates the correct answers in the integer case.
Topic archived. No new replies allowed.