练习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;
}