朱色虫居
Pages
Home
Featured Posts
2006/09/12
478-Points in Figures: Rectangles, Circles and Triangles
/*
"Points in Figures: Rectangles, Circles and Triangles"
Level:5.0
Date:2006/9/11
技巧:
長方形的判斷: x > 左上角的x && x < 右下角的x && y < 左上角的y && y > 右下角的y
圓形的判斷: (x - 圓心的x)^2 + (y - 圓心的y)^2 < 半徑^2 三角形的判斷: 面積比較法:若點在三角形內 ,則點與三頂點將形成三個三角形, 若其面積總和 > 原三角形面積 ,且誤差小於0.000001, 則點在三角形內
此法非最佳, 利用向量判斷是否線段相交, 不但較快, 也較省記憶體.
*/
#include
#include
struct shape{
char kind; //rectangle, circle or triangle
double x1;
double y1;
double x2;
double y2;
double x3;
double y3;
double radius;
}s[10];
double length(double x1, double y1, double x2, double y2);
double area(double a, double b, double c); //apply Heron's rule to calculate Triangle's Area.
main(){
const float epsilon = 0.000001; // use epsilon to guard against miscalculation.
double t1,t2,t3,t0; // calculate the area of triangles.
int i;
int no=1;
bool contain = false;
int len = 0;
double x,y;
char temp;
while(scanf("%c",&temp)){
if(temp == 'r'){
scanf("%lf %lf %lf %lf",&s[len].x1,&s[len].y1,
&s[len].x2,&s[len].y2);
s[len].kind = 'r';
s[len].radius = 0;
s[len].x3 = 0;
s[len].y3 = 0;
len++;
}
else if (temp == 'c'){
scanf("%lf %lf %lf", &s[len].x1, &s[len].y1, &s[len].radius);
s[len].kind = 'c';
s[len].x2 = s[len].y2 = s[len].x3 = s[len].y3 = 0;
len++;
}
else if (temp == 't'){
scanf("%lf %lf %lf %lf %lf %lf",
&s[len].x1, &s[len].y1, &s[len].x2, &s[len].y2, &s[len].x3, &s[len].y3);
s[len].kind = 't';
s[len].radius = 0;
len++;
}
else if(temp == '*')
break;
}
while(scanf("%lf %lf",&x,&y)){
if(x == 9999.9 && y == 9999.9)
break;
for(i=0;i
s[i].x1 && x < s[i].x2 && y < s[i].y1 && y > s[i].y2){
printf("Point %d is contained in figure %d\n",no,i+1);
contain = true;
}
else if (s[i].kind == 'c' && (x-s[i].x1)*(x-s[i].x1)+(y-s[i].y1)*(y-s[i].y1)
< s[i].radius * s[i].radius){ printf("Point %d is contained in figure %d\n",no,i+1); contain = true; } else if (s[i].kind == 't'){ t0 = area(length(s[i].x1, s[i].y1, s[i].x2, s[i].y2), length(s[i].x1, s[i].y1, s[i].x3, s[i].y3), length(s[i].x2, s[i].y2, s[i].x3, s[i].y3)); t1 = area(length(x, y, s[i].x1, s[i].y1), length(x, y, s[i].x2, s[i].y2), length(s[i].x1, s[i].y1, s[i].x2, s[i].y2)); t2 = area(length(x, y, s[i].x1, s[i].y1), length(x, y, s[i].x3, s[i].y3), length(s[i].x1, s[i].y1, s[i].x3, s[i].y3)); t3 = area(length(x, y, s[i].x3, s[i].y3), length(x, y, s[i].x2, s[i].y2), length(s[i].x3, s[i].y3, s[i].x2, s[i].y2)); if(t1+t2+t3-t0 <= epsilon){ printf("Point %d is contained in figure %d\n",no,i+1); contain = true; } } } if(contain == false) printf("Point %d is not contained in any figure\n",no); no++; contain = false; } } double length(double x1, double y1, double x2, double y2){ return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } double area(double a, double b, double c){ double s = (a+b+c)/2; return sqrt(s*(s-a)*(s-b)*(s-c)); }
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment