此题难度不大,但是收获不小,在计算中尽量少用除法。。。下面给出两个代码,其中一个是错误的答案,比较两者的区别。。。
//wrong
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
struct Point{
double x, y;
Point(double x = 0, double y = 0):x(x), y(y) { }
};
typedef Point Vector;
double Dot(Vector A, Vector B) {
return A.x * B.x + A.y * B.y;
}
double Length(Vector A) {
return sqrt(Dot(A, A));
}
double Angle(Vector A, Vector B) {
return acos(Dot(A, B)/Length(A)/Length(B));
}
int main()
{
int T;
double rad;
double PI = 3.1415926;
int x1, y1, x2, y2;
while(T--) {
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
Vector tmp1(x1, y1);
Vector tmp2(x2, y2);
rad = Angle(tmp1, tmp2);
cout << "rad = " << rad << endl;
printf("%.2lf\n", rad*180/PI);
}
return 0;
}
//AC
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main(){
double PI = 3.1415926;
int T;
double dot, m;
scanf("%d", &T);
double x1, y1, x2, y2;
while(T--) {
cin >> x1 >> y1 >> x2 >> y2;
dot = x1*x2 + y1*y2;
m = sqrt((x1*x1+y1*y1)*(x2*x2+y2*y2));
cout << "acos = " << acos(dot/m) << endl;
double res = acos(dot/m)*180/PI;
printf("%.2lf\n", res);
}
}
/************
4
1 1 2 2
1 1 1 0
***************/