问题描述
我已经开始使用 cfenv 来检查变量的上溢和下溢,而且我已经看到您还可以检查其他内容,例如除以零和“无效”。
它通过无效运算给出的例子是-1的平方根,它有效:
#include <cfenv>
#include <cmath>
#include <iostream>
int main() {
std::feclearexcept(FE_INVALID);
double invalid_var = 0;
std::cout << "Invalid flag before: " << (bool)std::fetestexcept(FE_INVALID) << std::endl;
invalid_var = sqrt(-1);
std::cout << "Invalid flag after: " << (bool)std::fetestexcept(FE_INVALID) << std::endl;
return 0;
}
之前的无效标志:0
之后的无效标志:1
问题是在我的代码中我不使用 sqrt 作为平方根,我使用数学等价的 x^(1/2)。使用 pow 而不是 sqrt 它给出了结果 1,并且没有标志:
#include <cfenv>
#include <cmath>
#include <iostream>
int main() {
std::feclearexcept(FE_INVALID);
double invalid_var = 0;
std::cout << "Invalid flag before: " << (bool)std::fetestexcept(FE_INVALID) << std::endl;
invalid_var = pow(-1,1/2);
std::cout << "Invalid flag after: " << (bool)std::fetestexcept(FE_INVALID) << std::endl;
return 0;
}
之前的无效标志:0
之后的无效标志:0
有什么我可以做的吗?我是 C++ 新手,我不知道您使用的数学函数和异常类型,也许我给它的方法有误。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)