This question already has answers here:
Checking for underflow/overflow in C++?

(3个答案)



How to detect double precision floating point overflow and underflow?

(4个答案)


6年前关闭。




我编写了以下C++代码来检查下溢。不确定这是否是一个好习惯。
#include <limits>
#include <iostream>

int main()
{
    float d = 1.e-29;
    std::cout<<"d: "<<d<<" underflow? "<<(d<std::numeric_limits<float>::min())<<std::endl;
    d = 1.e-59;
    std::cout<<"d: "<<d<<" underflow? "<<(d<std::numeric_limits<float>::min())<<std::endl;
}

打印输出是
d: 1e-29 underflow? 0
d: 0 underflow? 1

最佳答案

在将变量与标准限制进行比较后,便无法检查下溢或上溢。

简单的例子:

int v1 = INT_MAX;
int v2 = INT_MAX;
int v3 = v1 * v2;

表达式v1 * v2导致溢出。但是,v3的值仍将是有效的int

您必须在v1 * v2之前执行检查,以确定是否会导致溢出。

关于c++ - 我的代码可以安全检查下溢吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23280326/

10-09 06:32
查看更多