uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1288
给出三条中线的长度,求三角形的面积。
套公式可以过,不过我不明白为什么我求出三条边以后再判断是否能构成合法的三角形是错的。
AC的代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <cmath> 6 7 using namespace std; 8 9 template<class T> T sqr(T x) { return x * x;} 10 11 double work(double x[], double m[]) { 12 double s = 0.0, t[3]; 13 for (int i = 0; i < 3; i++) { 14 if (m[i] <= 0) return -1.0; 15 if (m[i] + m[(i + 1) % 3] <= m[(i + 2) % 3]) return -1.0; 16 } 17 for (int i = 0; i < 3; i++) { 18 if (x[i] <= 0) return -1.0; 19 // if (x[i] + x[(i + 1) % 3] <= x[(i + 2) % 3]) return -1.0; 20 t[i] = sqrt(x[i]); 21 s += t[i]; 22 } 23 s /= 2.0; 24 return sqrt(s * (s - t[0]) * (s - t[1]) * (s - t[2])); 25 } 26 27 int main() { 28 double med[3], x[3]; 29 while (true) { 30 for (int i = 0; i < 3; i++) if (!(cin >> med[i])) return 0; 31 for (int i = 0; i < 3; i++) { 32 x[i] = (sqr(med[i]) + sqr(med[(i + 1) % 3])) * 2.0 - sqr(med[(i + 2) % 3]); 33 x[i] *= 4.0 / 9.0; 34 // cout << x[i] << endl; 35 } 36 printf("%.3f\n", work(x, med)); 37 } 38 }
我觉得是正确的一份代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <cmath> 6 7 using namespace std; 8 9 template<class T> T sqr(T x) { return x * x;} 10 11 double work(double x[]) { 12 double s = 0.0, t[3]; 13 for (int i = 0; i < 3; i++) { 14 if (x[i] <= 0) return -1.0; 15 if (x[i] + x[(i + 1) % 3] <= x[(i + 2) % 3]) return -1.0; 16 t[i] = sqrt(x[i]); 17 s += t[i]; 18 } 19 s /= 2.0; 20 return sqrt(s * (s - t[0]) * (s - t[1]) * (s - t[2])); 21 } 22 23 int main() { 24 double med[3], x[3]; 25 while (true) { 26 for (int i = 0; i < 3; i++) if (!(cin >> med[i])) return 0; 27 for (int i = 0; i < 3; i++) { 28 x[i] = (sqr(med[i]) + sqr(med[(i + 1) % 3])) * 2.0 - sqr(med[(i + 2) % 3]); 29 x[i] *= 4.0 / 9.0; 30 // cout << x[i] << endl; 31 } 32 printf("%.3f\n", work(x)); 33 } 34 }
产生差别的数据是 2 3 4。
对于这个问题,我已经发邮件给uva的管理员,希望能等到答复。或者有大神能解答就更好了~
——written by Lyon