C++ 上溢和下溢(overflow underflow)

存储在内存中的数值都有一个允许的数值范围。当计算结果超出了数值范围,就BOOM~~

#include <iostream>

using namespace std;

int main()
{
    float x=2.5e30, y=1.0e30;
    float z = x * y ;
    // z应为2.5e60,然而这超出了范围
    cout<<"z :  "<<z<<endl;
    // z为inf(无穷大)
    cout<<"x :  "<<x<<endl;
    cout<<"x :  "<<y<<endl;
    // 这种错误称为overflow

    cout << "~~~~~~~~~~~~~~~~~~~~~~" <<endl;
    // 华丽的分割线

    x=2.5e-30, y=1.0e30;
    z = x / y;
    // z的值应为2.5e-60,然而这和overflow的错误是类似的
    cout<<"z :  "<<z<<endl;
    // 在我的系统中,发生指数下溢时,结果置为0
    cout<<"x :  "<<x<<endl;
    cout<<"y :  "<<y<<endl;
    // 这种错误称为underflow
    return 0;
}


原文地址:https://www.cnblogs.com/Genesis2018/p/9079830.html