zoukankan      html  css  js  c++  java
  • a<b 与 a-b<0 的区别

     计算机中的不等式等价移项,需考虑数据的默认转换问题

    有多少人想骂人?

    shuting(音:虾挺 ,译:关闭,消停,闭嘴)

    且看如下小段代码: 

        public static void main(String[] args) {
            int maxValue = Integer.MAX_VALUE;
            int minValue = Integer.MIN_VALUE;
    
            if (maxValue < minValue) {
                System.out.println("maxValue < minValue");
            }
            System.out.println("minValue = " + (minValue));
            System.out.println("maxValue = " + (maxValue));
            System.out.println("minValue - maxValue = " + (minValue - maxValue));
            System.out.println("maxValue - minValue = " + (maxValue - minValue));
            if (maxValue - minValue < 0) {
                System.out.println("maxValue - minValue < 0");
            }
        }

    执行结果:

    1 b = -2147483648
    2 a = 2147483647
    3 b - a = 1
    4 a - b = -1
    5 a - b < 0

    这里出问题的原因是:默认转换所导致——

    请看看这就清晰些:

     1     public static void main(String[] args) {
     2         int maxValue = Integer.MAX_VALUE;
     3         int minValue = Integer.MIN_VALUE;
     4         System.out.println("最大值:Integer.MAX_VALUE = " + (maxValue));
     5         int a1 = maxValue+1;
     6         System.out.println("Integer.MAX_VALUE + 1 ——>" + (a1) );
     7         int a2 = maxValue+2;
     8         System.out.println("Integer.MAX_VALUE + 2 ——>" + (a2) );
     9         int a3 = maxValue+5;
    10         System.out.println("Integer.MAX_VALUE + 5 ——>" + (a3) );
    11         
    12         System.out.println("------------");
    13         
    14         System.out.println("最小值:Integer.MIN_VALUE = " + (minValue));
    15         int b1 = minValue-1;
    16         System.out.println("Integer.MIN_VALUE - 1 ——>" + (b1) );
    17         int b2 = minValue-2;
    18         System.out.println("Integer.MIN_VALUE - 2 ——>" + (b2) );
    19         int b3 = minValue-5;
    20         System.out.println("Integer.MIN_VALUE - 5 ——>" + (b3) );
    21     }

    执行结果:

    1 最大值:Integer.MAX_VALUE = 2147483647
    2 Integer.MAX_VALUE + 1 ——>-2147483648
    3 Integer.MAX_VALUE + 2 ——>-2147483647
    4 Integer.MAX_VALUE + 5 ——>-2147483644
    5 ------------
    6 最小值:Integer.MIN_VALUE = -2147483648
    7 Integer.MIN_VALUE - 1 ——>2147483647
    8 Integer.MIN_VALUE - 2 ——>2147483646
    9 Integer.MIN_VALUE - 5 ——>2147483643

    原因:追溯到计算机以二进制运算,首位作为符号位。正数的首位为0(符号位),负数的首位为1(符号位)

    具体参见:[底层] 为什么Integer.MIN_VALUE-1会等于Integer.MAX_VALUE (可继续参看引用)

  • 相关阅读:
    Jenkins自动化测试环境搭建
    在windows上运行python程序
    DOS命令笔记
    批处理基础语法
    一键清理c盘垃圾文件--bat文件
    Centos7中打包docker离线包
    python之正则表达式使用
    LoadRunner11使用代理录制脚本
    快速查看日志脚本
    实现两种登录方式一键切换的脚本及相关知识点
  • 原文地址:https://www.cnblogs.com/bridgestone29-08/p/13997230.html
Copyright © 2011-2022 走看看