kevin8888,
你直接使用 try catch 是不行的,因为C++ 没有为基本数据类型的数学运算定义过异常处理。
如果你想扑捉异常,那么你必须在代码中自己处理。 4楼的 wfgb 说的是对的。
我给你一个相对完整的代码:
[CODE]
#include <iostream>
double hmean(double a, double b);
int main()
{
double x, y, z;
std::cout<<"Enter two numbers: ";
while(std::cin>>x>>y)
{
try{
z = hmean(x, y);
}
catch(const char * s)
{
std::cout<<s<<std::endl;
std::cout<<"Enter a new pair of numbers: ";
continue;
}
std::cout<<"Harmonic mean of "<<x<<" and "<<y<<" is "<<z<<std::endl;
std::cout<<"Enter next set of numbers <q to quit>: ";
}
std::cout<<" Bye!\n";
return 0;
}
double hmean(double a, double b)
{
if(a == -b)
throw "bad hmean() arguments: a = -b not allowed";
return 2.0 * a * b / (a + b);
}
[/CODE]