C/C中的feholdException()++

这个 FeholdException() C/C++中的函数首先将当前浮点环境保存在fenv_t对象中,然后重置所有浮点状态标志的当前值。feholdexcept()函数在中定义 cfenv 中的头文件 C++ 而且 芬夫。H 中的头文件 C . 语法:

null
int feholdexcept( fenv_t* envp )

参数: 该函数只接受一个强制参数 envp 它是指向一个对象的指针 类型 芬弗特 它存储浮点环境的当前状态。 返回值: 函数在两种情况下返回int值:

  • 如果函数成功完成,则返回0。
  • 失败时,它返回一个非零整数。

下面的程序说明了上述功能。 项目1:

CPP

// C++ program to illustrate the
// feholdexcept() function
#include <bits/stdc++.h>
#pragma STDC FENV_ACCESS on
// function to divide
double divide( double x, double y)
{
// environment variable
fenv_t envp;
// do the devision
double ans = x / y;
// use the function feholdexcept
feholdexcept(&envp);
// clears exception
feclearexcept(FE_OVERFLOW | FE_DIVBYZERO);
return ans;
}
int main()
{
// It is a combination of all of
// the possible floating-point exception
feclearexcept(FE_ALL_EXCEPT);
double x = 10;
double y = 0;
// it returns the division of x and y
printf ( "x/y = %f" , divide(x, y));
// the function does not throw
// any exception on division by 0
if (!fetestexcept(FE_ALL_EXCEPT)) {
printf ( "No exceptions raised" );
}
return 0;
}


输出:

x/y = infNo exceptions raised

项目2:

CPP

// C++ program to illustrate the
// feholdexcept() function
#include <bits/stdc++.h>
#pragma STDC FENV_ACCESS on
using namespace std;
// function to print raised exceptions
void raised_exceptions()
{
cout << "Exceptions raised are : " ;
if (fetestexcept(FE_DIVBYZERO))
cout << " FE_DIVBYZERO" ;
else if (fetestexcept(FE_INVALID))
cout << " FE_INVALID" ;
else if (fetestexcept(FE_OVERFLOW))
cout << " FE_OVERFLOW" ;
else if (fetestexcept(FE_UNDERFLOW))
cout << " FE_UNDERFLOW" ;
else
cout << " No exception found" ;
return ;
}
// Driver code
int main()
{
// environment variable
fenv_t envp;
// raise certain exceptions
feraiseexcept(FE_DIVBYZERO);
// print the raised exception
raised_exceptions();
// saves and clears current
// exceptions by feholdexcept function
feholdexcept(&envp);
// no exception found
raised_exceptions();
// restores the previously
// saved exceptions
feupdateenv(&envp);
raised_exceptions();
return 0;
}


输出:

Exceptions raised are :  FE_DIVBYZEROExceptions raised are :  No exception foundExceptions raised are :  FE_DIVBYZERO

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享