How to use feclearexcept() function to clear the floating-point exception in C++

4 Answers

0 votes
#include <iostream>
#include <cmath>
#include <cfenv> 
#include <cerrno>

using namespace std;

int main()
{
	errno = 0; feclearexcept(FE_ALL_EXCEPT);
	cout <<  "asin(1.2) = " << asin(1.2) << endl;
	if (errno == EDOM) perror("errno == EDOM");
	if (fetestexcept(FE_INVALID)) cout << "FE_INVALID raised" << endl;

	return 0;
}


/*
run:

asin(1.2) = -nan(ind)
errno == EDOM: Domain error
FE_INVALID raised

*/

 



answered Mar 12, 2016 by avibootz
0 votes
#include <iostream>
#include <cfenv>

using namespace std;

int main()
{
	double d = 0.0;

	feclearexcept(FE_ALL_EXCEPT);
	cout << "1.0/0.0 = " << 1.0 / d << endl;
	if (fetestexcept(FE_DIVBYZERO)) 
		cout << "division by zero" << endl;

	return 0;
}


/*
run:

1.0/0.0 = inf
division by zero

*//

 



answered Mar 14, 2016 by avibootz
0 votes
#include <iostream>
#include <cfenv>

using namespace std;

int main()
{
	double d = 1.0;

	feclearexcept(FE_ALL_EXCEPT);
	cout << "1.0/10 = " << d / 10 << endl;
	if (fetestexcept(FE_INEXACT))
		cout << "inexact result" << endl;

	return 0;
}


/*
run:

1.0/10 = 0.1
inexact result

*/

 



answered Mar 14, 2016 by avibootz
0 votes
#include <iostream>
#include <cfenv>
#include <cmath>

using namespace std;

int main()
{
	feclearexcept(FE_ALL_EXCEPT);
	cout << "sqrt(-1) = " << sqrt(-1) << endl;
	if (fetestexcept(FE_INVALID)) 
		cout << "invalid result" << endl;

	return 0;
}


/*
run:

sqrt(-1) = -nan(ind)
invalid result

*/

 



answered Mar 14, 2016 by avibootz
...