异常 abort()与返回错误码

1>调用函数终止程序

#include <iostream>
#include <cstdlib>     //for abort();  or  exit(x); x为0正常终止 非0非正常终止
double hmean (double a,double b);

int main(void)
{
 double x,y,z;
 std::cout<<"enter two numbers: ";
 while (std::cin>>x>>y)
 {
  z=hmean(x,y);
  std::cout<<"harmonic mean of "<<x<<" and "<<y
   <<" is "<<z<<std::endl;
  std::cout<<"enter next set of number <q to quit>: ";
    }
 std::cout<<"bye!\n";
 return 0;
}
/////////////////////////////////////////////
double hmean(double a,double b)
{
 if (a==-b)
 {
  std::cout<<"untenable to hmean()\n";
  std::exit(123);
 }
 return 2.0*a*b/(a+b);
}


2>返回错误码


#include <iostream>
#include <cfloat>     //for DBL_MAX
bool hmean (double a,double b,double * ans);//定义一个指针用以改变指向数据的值

int main(void)
{
 double x,y,z;
 std::cout<<"enter two numbers: ";
 while (std::cin>>x>>y)
 {
  if (hmean(x,y,&z))
  std::cout<<"harmonic mean of "<<x<<" and "<<y
   <<" is "<<z<<std::endl;
  else
   std::cout<<"please try again.\n";
  std::cout<<"enter next set of number <q to quit>: ";
    }
 std::cout<<"bye!\n";
 return 0;
}
bool hmean(double a,double b,double * ans)
{
 if (a==-b)
 {
  *ans=DBL_MAX;
  return false;
 }
 else
 {
     *ans=2.0*a*b/(a+b);
  return true;
 }
}

posted @ 2007-03-10 14:10  Edward Xie  阅读(536)  评论(0)    收藏  举报