abort函数位于cstdlib头文件里,它会终止程序,并根据具体实现返回一个值给调用这个程序的系统或进程,而exit函数单纯终止程序,不会返回消息。
abort的具体实现:
#include <iostream>
#include <cstdlib>
using namespace std;
double hmean(double a,double b){
if(a==-b){
cout<<"aerror!a+b=0";
abort();
}
return 2*a*b/(a+b);
}
int main(){
double x,y,z;
cout<<"Enter two numbers:";
while(cin>>x>>y){
z=hmean(x,y);
cout<<"Harmonic mean of"<<x<<"and"<<y<<"is"<<z<<endl;
cout<<"Enter next set of numbers:"
}
cout<<"Bye"<<endl;
return 0;
}
还有一种类似于文件读写时在文件末尾设置特殊字符EOF的操作,在程序运行时若遇错则返回错误码:
返回错误码的方法可以不终止程序,指出错误,跳过它重新输入
#include <iostream>
#include <cfloat> //DBL_MAX在cfloat头文件中
using namespace std;
bool hmean(double a,double b,double *z){
if(a==-b){
*z=DBL_MAX; //用一个变量来储存错误值,并返回false
return false;
}
*z=2*a*b/(a+b);
return true;
}
int main(){
double x,y,*z;
cout<<"Enter two numbers:";
while(cin>>x>>y){
if(hmean(x,y)){ //判断函数返回值
cout<<"Harmonic mean of"<<x<<"and"<<y<<"is"<<*z<<endl;
cout<<"Enter next set of numbers:"
}
else{
cout<<"error!a+b=0"<<endl;
cout<<"Please enter another pair of numbers:";
}
}
cout<<"Bye"<<endl;
return 0;
}