您的位置:首页 > 编程语言 > C语言/C++

c++异常处理,,,同时处理除数为0以及开根号内部不能小于0

2015-07-04 00:23 267 查看


1001:异常——排除表达式的异常

Time/Memory Limit:1000 MS/32768 K 
Submitted: 46 Accepted: 35




 Problem Description

 设有表达式 (a+b/c),对其开根号,计算表达式的值,要求能排除除数为0及根号小于0的异常。




 Input

 输入数据有多组。




 Output

 对于每组输入数据,输出占两行(具体输出格式参见输出样例)




 Sample Input

5 -100 2
23 35 0
43 75 15





 Sample Output

a=5,b=-100,c=2
Negative numbers can not square root!
a=23,b=35,c=0
Divisor can not be 0!
a=43,b=75,c=15
The result is:6.9282





 Author

wj


 Source

2014 1 2 异常与<<重载(VIII)




 Recommend

zh

#include<iostream>

#include<cmath>

using namespace std;

int chu=0;

double fu=0;

double F(double a,double b,double c){

if(c==0)

  throw chu;

if((a+b/c)<0)

  throw fu;

return sqrt(a+b/c);

}

int main(){
double a,b,c;

    while(cin>>a>>b>>c){
cout<<"a="<<a<<","<<"b="<<b<<","<<"c="<<c<<endl;
try{
       cout<<"The result is:"<<F(a,b,c)<<endl;
}
catch(int){
cout<<"Divisor can not be 0!\n";
}
catch(double){
cout<<"Negative numbers can not square root!\n";
}
}

return 0;
}

对于多种问题不主张这种写法,

可以用类来try  catch;

由于只有2个问题,故用int double 2个作为处理问题的端口
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: