不同数据类型取值范围【实例:防止溢出的阶乘计算】

版权声明:根号v587版权所有 https://blog.csdn.net/hcmdghv587/article/details/81879213
#include <iostream>
#include <climits>  
/*<climits>头文件定义的符号常量
CHAR_MIN       char的最小值
SCHAR_MAX      signed char 最大值
SCHAR_MIN       signed char 最小值
UCHAR_MAX      unsigned char 最大值
SHRT_MAX       short 最大值
SHRT_MIN       short 最小值
USHRT_MAX      unsigned short 最大值
INT_MAX       int 最大值
INT_MIN        int 最小值
UINT_MAX       unsigned int 最大值
UINT_MIN        unsigned int 最小值
LONG_MAX      long最大值
LONG_MIN       long最小值
ULONG_MAX      unsigned long 最大值
FLT_MANT_DIG    float 类型的尾数
FLT_DIG         float 类型的最少有效数字位数
FLT_MIN_10_EXP   带有全部有效数的float类型的负指数的最小值(以10为底)
FLT_MAX_10_EXP    float类型的正指数的最大值(以10为底)
FLT_MIN        保留全部精度的float类型正数最小值
FLT_MAX        float类型正数最大值*/
using namespace std;
class Factorial
{
public:
    Factorial(int);
    bool check(void);
    void calculate(void);
private:
    int num;
    unsigned long result;
    friend ostream & operator<<(ostream &, Factorial &);
};

Factorial::Factorial(int num)
{
    this -> num = num;
    calculate();
}
void Factorial::calculate(void)
{
    result = 1;
    for (int i = 1; i <= num; i++)
    {
        result *= i;
    }
}
bool Factorial::check(void)
{
    unsigned long max;
    max = ULONG_MAX;
    for (int i = 1; i <= num; i++)
    {
        max /= i;
    }
    return (max >= 1);
}
ostream & operator<<(ostream & os, Factorial & rhs)
{
    if (rhs.check())
    {
        os << rhs.result;
    }
    else
    {
        os << "溢出!";
    }
    return os;
}

int main()
{
    for (int i = 1; i <= 20; i++) 
    {
        Factorial *fact = new Factorial(i);
        cout << i << "的阶乘为:" << *fact << endl;
        delete fact;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hcmdghv587/article/details/81879213