第五章 5.6.3节练习

练习5.23

编写一段程序,从标准输入读取两个整数,输入第一个数除以第二个数的结果。

解答:

#include <iostream>

using namespace std;

int main(){
	int a, b;
	cin >> a >> b;
	cout << a / b << endl;
}

练习5.24

修改你的程序,使得当第二个数是0时抛出异常。先不要设定catch子句,运行程序并真的为除数输入0,看看会发生什么?

解答:

#include <iostream>
#include <stdexcept>

using namespace std;

int main(){
	int a, b;
	cin >> a >> b;
	if (b == 0){
		throw range_error("The denominator is 0");
	}
	cout << a / b << endl;
}

练习5.26

修改上一题的程序,使用try语句块去捕捉异常。catch子句应该为用户输出一条提示信息,询问其是否输入新数并重新执行try语句块的内容。

解答:

<pre name="code" class="cpp">#include <iostream>
#include <stdexcept>
#include <string>

using namespace std;

int main(){
	int a, b;
	string choose;
	try{
		cin >> a >> b;
		if (b == 0){
			throw range_error("The denominator is 0");
		}
	}
	catch (range_error &e){
		cout << e.what()<< endl;
		while (1){
			cout << "Do you want to type other num for denominator?[y/N]" << endl;
			cin >> choose;
			if (choose.at(0) == 'y' || choose.at(0) == 'Y'){
				cin >> b;
				if (b == 0){
					cout << "The denominator is 0" << endl;
					continue;
				}
				else{
					break;
				}
			}
			else{
				break;
			}
		}
	}
	cout << a / b << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值