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"*/
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.