zoukankan      html  css  js  c++  java
  • 编程计算int类型整数的最大值和最小值

    方法一:将一个int类型整数不断加1,加到最大值,再加1,就变成负值(最小值)

     最大值就是除最高位外,其余位都为1,-1即是所有位全部是1,右移1位后最高位变0
       最小值即是最高位为1,其余位为0,所以最大值+1之后就变成了最小值

    //#include <stdio.h>
    #include <iostream>
    //#include <limits.h>
    
    using namespace std;
    
    int main(){
        int i = 0, min, max;
        while(1){
            if(i+1<=0){
                max = i;
                min = i+1;
                break;
            }
            i++;
        }
        cout << "min is " << min <<endl;
        cout << "max is " << max << endl;
        getchar();
        return 0;
    }

    方法二:利用标准头文件limits.h,该文件包含一些很有用的常量,它们定义了各种类型所能容纳的值,其中int类型最大值最小值的预定义为

    #define INT_MAX 2147483647
    #define INT_MIN (-INT_MAX-1)
    所以可以利用此头文件打印int类型整数的最小值和最大值。
    //#include <stdio.h>
    #include <iostream>
    #include <limits.h>
    
    using namespace std;
    
    int main(){
        cout << "最小值是:" << INT_MIN << endl;
        cout << "最大值是:" << INT_MAX << endl;
        getchar();
        return 0;
    }

    方法三:C++模板numeric_limits(对模板不熟悉啊)可以参考:

    http://blog.163.com/wujiaxing009@126/blog/static/7198839920124135147911/

    代码:

    #include <iostream>
    #include <limits>
    using namespace std;
    
    int main(){
        cout<<(numeric_limits<int>::max)()<<endl;
        cout<<(numeric_limits<int>::min)()<<endl;
        cout<<(numeric_limits<size_t>::max)()<<endl;
        cout<<(numeric_limits<size_t>::min)()<<endl;
        cout<<(numeric_limits<float>::max)()<<endl;
        cout<<(numeric_limits<float>::min)()<<endl;
        cout<<(numeric_limits<double>::max)()<<endl;
        cout<<(numeric_limits<double>::min)()<<endl;
        getchar();
        return 0;
    }

    以上是在网上看到的三种方法,学习学习。

  • 相关阅读:
    Netty回调与Channel执行流程分析
    Netty执行流程分析与重要组件介绍
    HBase 介绍
    Java文件上传下载原理
    ngxtop安装和使用
    开启Nginx监控 with-http_stub_status_module
    Spring 事务模板方法设计模式
    Spring 事务管理
    JdkDynamicAopProxy 拦截器链的获得与递归执行
    CgLib实现AOP
  • 原文地址:https://www.cnblogs.com/gkfeng/p/4573351.html
Copyright © 2011-2022 走看看