下列程序的功能是:输入数组下标和除数,从数组中取出下标对应的数组元素作为被除数,输出除法运算的结果。例如, 输入:9 5 输出:2 捕获程序数组下标越界错误,给出相应的提示,例如, 输入:10 5 输出:10 out of bound 输入:-1 5 输出:-1 out of bound 捕获程序数组下标除零错误,给出相应的提示,例如, 输入:9 0 输出:divide by 0 部分代码已给出,请将代码补充完整。#include <iostream> using namespace std; int main() { int index, dividend, divisor, result; int array[10]={1,2,3,4,5,6,7,8,9,10}; try { cin >> index >> divisor; if( index < 0 || index>9) throw index; if(divisor==0) throw divisor; dividend = array[index]; result = dividend / divisor; cout << result << endl; } return 0; }
时间: 2023-07-16 22:11:26 浏览: 65
补充完整的代码如下:
```c++
#include <iostream>
using namespace std;
int main()
{
int index, dividend, divisor, result;
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
try
{
cin >> index >> divisor;
if (index < 0 || index > 9)
throw index; // 抛出数组下标越界异常
if (divisor == 0)
throw divisor; // 抛出除数为0异常
dividend = array[index];
result = dividend / divisor;
cout << result << endl;
}
catch (int e) // 捕获异常
{
if (e == index)
cout << index << " out of bound" << endl;
if (e == divisor)
cout << "divide by 0" << endl;
}
return 0;
}
```
代码中使用了 try-catch 语句来捕获程序可能出现的异常。当输入的下标超出了数组范围或者除数为0时,程序会抛出相应的异常。在 catch 语句块中,根据抛出异常时传入的参数来判断是哪种异常,然后给出相应的提示信息。
阅读全文