zoukankan      html  css  js  c++  java
  • -2147483648的绝对值

    求整型绝对值的有以下方法:

    1. int abs = a > 0 ? a : -a;
    2. Math.abs()函数

    以int整型为例,取值范围是-2147483648 ~ 2147483647,对于-2147483647 ~ 2147483647范围内的数字,使用上面的方法没有问题,但是对于-2147483648 取绝对值的时候却会直接返回该值。

    以下是Java中Math.abs()函数的源码

    /**
     * Returns the absolute value of an {@code int} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     *
     * <p>Note that if the argument is equal to the value of
     * {@link Integer#MIN_VALUE}, the most negative representable
     * {@code int} value, the result is that same value, which is
     * negative.
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
    */
    public static int abs(int a) {
        return (a < 0) ? -a : a;
    }
    
    /**
     * Returns the absolute value of a {@code long} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     *
     * <p>Note that if the argument is equal to the value of
     * {@link Long#MIN_VALUE}, the most negative representable
     * {@code long} value, the result is that same value, which
     * is negative.
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static long abs(long a) {
        return (a < 0) ? -a : a;
    }
    

    下面是各个值的二进制:

    二进制
    -2147483647原码 1111 1111 1111 1111 1111 1111 1111 1111
    -2147483647补码 1000 0000 0000 0000 0000 0000 0000 0001
    -1原码 1000 0000 0000 0000 0000 0000 0000 0001
    -1补码 1111 1111 1111 1111 1111 1111 1111 1111
    -2147483648 补码 1000 0000 0000 0000 0000 0000 0000 0000
  • 相关阅读:
    pip下载速度慢&如何使用国内源提高速度
    pip更新安装删除包
    如何让VSCode同时打开(显示)多个项目
    JavaScript计算器
    在Ubuntu下搭建Android开发环境(AndroidStudio)
    在Windows中安装vim
    硬盘分区教程
    如何在Windows系统下使用you-get下载网上的媒体资源
    mencoder及ffmpeg的基本命令
    笔记本如何不按Fn键就能实现F键的功能
  • 原文地址:https://www.cnblogs.com/cdbb/p/13252034.html
Copyright © 2011-2022 走看看