用try-catch函数来检查一元二次方程式的实根

1.try{}函数体内是用来检查的部分。

	try
	{
		x1=p+q(a,b,c);
		x2=p-q(a,b,c);
		cout<<x1<<' '<<x2<<' '<<"try"<<endl;
	}

2.如果检查到try中有错误就会抛出信息,用throw关键字来抛出。

double q(double a,double b,double c)
{
	double x,d;
	d=b*b-4*a*c;
	if(d<0)throw d;	//如果出现错误,就会执行throw 
	return sqrt(d)/2*a;
	return x/(2*a);
}

3.抛出了throw之后,程序就会直接跳转到抓捕环节,用catch关键字来表示。

	catch(double d)
	{
		cout<<a<<' '<<b<<' '<<c<<' '<<d<<"error!"<<endl;
	}

举例:

完整含try-throw代码:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	double q(double ,double ,double );
	double a,b,c,p,x1,x2;
	cin>>a>>b>>c;
	p=-b/(2*a);
	try
	{
		x1=p+q(a,b,c);
		x2=p-q(a,b,c);
		cout<<x1<<' '<<x2<<' '<<"try"<<endl;
	}
	catch(double d)
	{
		cout<<a<<' '<<b<<' '<<c<<' '<<d<<"error!"<<endl;
	}
	cout<<endl;
	return 0;
}
double q(double a,double b,double c)
{
	double x,d;
	d=b*b-4*a*c;
	if(d<0)throw d;	//如果出现错误,就会执行throw 
	return sqrt(d)/2*a;
	return x/(2*a);
}

当输入错误数据时:

可以看到只出现了,抓捕环节的数据,没有try函数体中的cout输出。

当输入正确数据时:

可以发现,抓捕环节的cout没有执行,因为输入数据正确。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值