计算几何讲解:
一个比较好的范例:
代码:
#includestruct node { double x1, y1; double x2, y2; }l[110]; double X(double a, double b, double c, double d) { return a*d - b*c; } int judge(int i, int j) { double a = X(l[i].x1-l[j].x1, l[i].y1-l[j].y1, l[j].x2-l[j].x1, l[j].y2-l[j].y1); double b = X(l[i].x2-l[j].x1, l[i].y2-l[j].y1, l[j].x2-l[j].x1, l[j].y2-l[j].y1); double c = a*b; double d = X(l[j].x1-l[i].x1, l[j].y1-l[i].y1, l[i].x2-l[i].x1, l[i].y2-l[i].y1); double e = X(l[j].x2-l[i].x1, l[j].y2-l[i].y1, l[i].x2-l[i].x1, l[i].y2-l[i].y1); double f = d*e; if(c <= 0 && f <= 0) return 1; return 0; } int main() { int n, i, j; //freopen("data.in", "r", stdin); while(scanf("%d", &n), n) { int ans = 0; for(i = 1; i <= n; i++) scanf("%lf%lf%lf%lf", &l[i].x1, &l[i].y1, &l[i].x2, &l[i].y2); for(i = 1; i < n; i++) for(j = i+1; j <= n; j++) { if(judge(i, j)) ans++; } printf("%d\n", ans); } return 0; }