?? 例14.1.txt
字號(hào):
例14.1 給出三角形的三邊a,b,c,求三角形的面積。只有a+b>c,b+c>a,c+a>b時(shí)才能構(gòu)成三角形。設(shè)置異常處理,對(duì)不符合三角形條件的輸出警告信息,不予計(jì)算。
先寫出沒有異常處理時(shí)的程序:
#include <iostream>
#include <cmath>
using namespace std;
int main( )
{double triangle(double,double,double);
double a,b,c;
cin>>a>>b>>c;
while(a>0 && b>0 && c>0)
{cout<<triangle(a,b,c)<<endl;
cin>>a>>b>>c;
}
return 0;
}
double triangle(double a,double b,double c)
{double area;
double s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
return area;
}
修改后的程序如下:
#include <iostream>
#include <cmath>
using namespace std;
void main( )
{double triangle(double,double,double);
double a,b,c;
cin>>a>>b>>c;
try//在try塊中包含要檢查的函數(shù)
{while(a>0 && b>0 && c>0)
{cout<<triangle(a,b,c)<<endl;
cin>>a>>b>>c;
}
}
catch(double) //用catch捕捉異常信息并作相應(yīng)處理
{cout<<″a=″<<a<<″,b=″<<b<<″,c=″<<c<<″,that is not a triangle!″<<endl;}
cout<<″e(cuò)nd″<<endl;
}
double triangle(double a,double b,double c) //計(jì)算三角形的面積的函數(shù)
{double s=(a+b+c)/2;
if (a+b<=c||b+c<=a||c+a<=b) throw a; //當(dāng)不符合三角形條件拋出異常信息
return sqrt(s*(s-a)*(s-b)*(s-c));
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -