1. 程式人生 > >計算幾何專題(計算兩圓相交面積)

計算幾何專題(計算兩圓相交面積)

There are two circles in the plane (shown in the below picture), there is a common area between the two circles. The problem is easy that you just tell me the common area. Input
There are many cases. In each case, there are two lines. Each line has three numbers: the coordinates (X and Y) of the centre of a circle, and the radius of the circle.
Output
For each case, you just print the common area which is rounded to three digits after the decimal point. For more details, just look at the sample.
Sample Input
0 0 2
2 2 1
Sample Output

0.108

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
#define PI acos(-1.0)
int main(){
    double a1,b1,r1,a2,b2,r2,d;
    double A1,A2,s1,s2,s;                
	while(~scanf("%lf%lf%lf%lf%lf%lf",&a1,&b1,&r1,&a2,&b2,&r2)){
        d=sqrt((a2-a1)*(a2-a1)+(b2-b1)*(b2-b1)); //求圓心距
        if(d>=r1+r2)   printf("0.000\n");     //兩圓相離或相外切
        else if(d<=fabs(r1-r2) && d>=0) {   //內切
        	if(r1>r2)  printf("%0.3lf\n",PI*r2*r2);
            else   printf("%0.3lf\n",PI*r1*r1);
        }
        else
        { 
            A1=2*acos((d*d+r1*r1-r2*r2)/(2*d*r1)); //求以圓心為頂點與兩圓交點連線的角
            A2=2*acos((d*d+r2*r2-r1*r1)/(2*d*r2));
            s1=0.5*r1*r1*sin(A1)+0.5*r2*r2*sin(A2);
            s2=A1/2*r1*r1+A2/2*r2*r2;
            s=s2-s1;
            printf("%0.3lf\n",s);
        }
    }
    return 0;
}