2018年2月28日 星期三

[C_MM159-易] 給定三邊長求三角形面積(C++)

[C_MM159-易] 給定三邊長求三角形面積

Problem Description 
小明想利用三線段做出一個三角形,並且計算出這個三角形的面積出來,因為圍出來的三角形不一定知道它的高是多少,因此可使用 「海龍公式」來求得面積。
海龍公式是假設三邊長的和為 s ,面積 S 可用下面公式表示:
CMM159.JPG
Input File Format 
Input 資料為給定的三邊長,資料型態為浮點數 。
Output Format 
先判斷此三邊長能否形成三角形,若可以再利用海龍公式算面積;如果不行,則 output 不能成為三角形 。
Example
Sample Input:Sample Output:
3
4
5
6.000000
5
5
6
12.000000
11
12
13
61.481705
4.5
5.2
8
10.928791
1
10
11
no answer


  1. #include <iostream>  
  2. #include <cmath>  
  3. #include <iomanip>  
  4. using namespace std;  
  5. double area(doubledoubledouble);  
  6. int main() {  
  7.     // [C_MM159-易] 給定三邊長求三角形面積  
  8.     double x, y, z;  
  9.     cin >> x >> y >> z;  
  10.     if(area(x, y, z) > 0)  
  11.     {  
  12.         cout << fixed << setprecision(6) << area(x, y, z) << endl;  
  13.     }  
  14.     else  
  15.     {  
  16.         cout << "no answer" << endl;  
  17.     }  
  18.     return 0;  
  19. }  
  20. double area(double a, double b, double c){  
  21.     if(a+b>c && a+c>b && b+c>a)  
  22.     {  
  23.         double s = (a+b+c)/2;  
  24.         double S = sqrt(s*(s-a)*(s-b)*(s-c));  
  25.         return S;  
  26.     }  
  27.     else  
  28.     {  
  29.         return -1;  
  30.     }  
  31. }  

沒有留言:

張貼留言