在 C++ 中使用 cfenv 作为错误控制,使用 pow 作为 sqrt 的问题

问题描述

我已经开始使用 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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...