【发布时间】:2023-04-08 23:57:02
【问题描述】:
在使用带有 int 或 long long int 的 pow() 函数时,有什么方法可以捕获溢出。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a = 2;//or long long int a = 2
int b = 50;//or long long int b = 50
if(!exponentation_overflows(a,b))//some function to check if there is no overflow
{
cout<<pow(a,b)<<endl;
}
}
【问题讨论】:
-
你会如何想象浮点值溢出的样子?已经在精度失败时?或者不是在浮动表示的绝对最大值出现之前?
-
我可以考虑使用内联汇编来捕捉它,但我宁愿等着看是否有标准的方法来做到这一点。
-
您需要在en.cppreference.com/w/cpp/numeric/math/pow 中未指定的哪些错误处理?
-
AFAIK,标准没有定义返回整数类型的 pow 函数 - 因此您可以使用 std::isnan(answer) 检查返回值。不过,这可能取决于实现。在您的情况下, pow(a, b) 会将 a 提升为加倍并返回加倍。
标签: c++ overflow undefined-behavior