java求余的技巧汇总

 更新时间:2019年09月25日 08:31:21   作者:一天不进步,就是退步  
这篇文章主要给大家介绍了关于java求余技巧的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

背景

传说里玉皇大帝派龙王马上降雨到共光一带,龙王接到玉皇大帝命令,立马从海上调水,跑去共光施云布雨,但粗心又着急的龙王不小心把海里的鲸鱼随着雨水一起降落在了共光,龙王怕玉皇大帝责怪,灵机一动便声称他是派鱼到共光,希望百姓可以年年有余,并请求玉皇大帝将这条鱼任命为鱼神,保佑人间太平可以年年有余。

年年有余

java 求余操作初阶

java中也有余的规范【jls-15.17.3】,废话不说,直接上代码,从中我们可以学到很多技巧:

例1:

int a = 5%3; // 2
int b = 5/3; // 1
System.out.println("5%3 produces " + a +" (note that 5/3 produces " + b + ")");

相信大多数人都知道结果了:

5%3 produces 2 (note that 5/3 produces 1)

java 求余操作中阶

我们知道,正数不仅仅有正整数还有负整数,那么负数的情况下,会出现什么变化呢?

例2:

int c = 5%(-3); // 2
    int d = 5/(-3); // -1
    System.out.println("5%(-3) produces " + c +" (note that 5/(-3) produces " + d + ")");
    int e = (-5)%3; // -2
    int f = (-5)/3; // -1
    System.out.println("(-5)%3 produces " + e +" (note that (-5)/3 produces " + f + ")");
    int g = (-5)%(-3); // -2
    int h = (-5)/(-3); // 1
    System.out.println("(-5)%(-3) produces " + g +" (note that (-5)/(-3) produces " + h + ")");

能完全正确得到结果的就很少了吧?

          5%(-3) produces 2 (note that 5/(-3) produces -1)
          (-5)%3 produces -2 (note that (-5)/3 produces -1)
          (-5)%(-3) produces -2 (note that (-5)/(-3) produces 1)

为什么求余的结果是这样的呢?jls-15.17.3规范告诉我们:

The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.
It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

注意:求余的正负数给dividend(左边操作数)的符号位一致!

java 求余操作高阶

java求余操作不但支持整数还支持浮点数

class Test2 {
 public static void main(String[] args) {
 double a = 5.0%3.0; // 2.0
 System.out.println("5.0%3.0 produces " + a);
 double b = 5.0%(-3.0); // 2.0
 System.out.println("5.0%(-3.0) produces " + b);
 double c = (-5.0)%3.0; // -2.0
 System.out.println("(-5.0)%3.0 produces " + c);
 double d = (-5.0)%(-3.0); // -2.0
 System.out.println("(-5.0)%(-3.0) produces " + d);
 }
}

相信很多人可以根据整型的规则,得出正确的结果

5.0%3.0 produces 2.0
5.0%(-3.0) produces 2.0
(-5.0)%3.0 produces -2.0
(-5.0)%(-3.0) produces -2.0

补充一下,浮点型的求余有一些特殊的规则:

The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java programming language defines % on floating-point operations to behave in a manner analogous to that of the integer remainder operator; this may be compared with the C library function fmod. The IEEE 754 remainder operation may be computed by the library routine Math.IEEEremainder.

The result of a floating-point remainder operation is determined by the rules of IEEE 754 arithmetic:

If either operand is NaN, the result is NaN.
If the result is not NaN, the sign of the result equals the sign of the dividend.
If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
If the dividend is finite and the divisor is an infinity, the result equals the dividend.
If the dividend is a zero and the divisor is finite, the result equals the dividend.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r = n - (d ⋅ q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.
Evaluation of a floating-point remainder operator % never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.

java 求余操作骨灰级

学到这里,或许有人沾沾自喜,我都掌握了求余的所有规则,看来需要给你泼泼冷水:

public static void main(String[] args) {
    final int MODULUS = 3;
    int[] histogram = new int[MODULUS];
    // Iterate over all ints (Idiom from Puzzle 26)
    int i = Integer.MIN_VALUE;
    do {
    histogram[Math.abs(i) % MODULUS]++;
    } while (i++ != Integer.MAX_VALUE);
    for (int j = 0; j < MODULUS; j++)
    System.out.println(histogram[j] + " ");
  }

这个程序会打印什么?有人经过繁琐复杂的算出一个结果:

1431655765 1431655766 1431655765

但其实,上述程序运行报错:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2
at com.java.puzzlers.ModTest.main(ModTest.java:11)

为什么数组会出现索引 -2?奇怪吧?要回答这个问题,我们必须要去看看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;
 }

特意说明,如果是Integer#MIN_VALUE,返回负数

java里有很多小技巧,需要我们勤翻api和jsl,多学习多练习。

参考资料:

【1】https://baike.baidu.com/item/%E5%B9%B4%E5%B9%B4%E6%9C%89%E4%BD%99/7625174?fr=aladdin

【2】https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.17.3

【3】java解惑

总结

以上就是我在处理客户端真实IP的方法,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

相关文章

  • Java Spring 循环依赖解析

    Java Spring 循环依赖解析

    这篇文章主要介绍了Java Spring 循环依赖解析,Spring 现在其实是我们 Java 程序开发离不开的基础框架,个人觉得除了 JDK 我们用得最多的 Java 中间件就是 Spring ,今天我们一起来学习一下 Spring 的循环依赖。下面详细内容需要的小伙伴可以参考一下
    2022-02-02
  • spring mvc 组合mybatis框架实例详解

    spring mvc 组合mybatis框架实例详解

    本项目采用 maven 结构,主要演示了 spring mvc + mybatis,controller 获取数据后以json 格式返回数据。对spring mvc 组合mybatis的方法感兴趣的朋友可以参考下本文
    2018-01-01
  • Spring Boot(三)之找回熟悉的Controller,Service

    Spring Boot(三)之找回熟悉的Controller,Service

    这篇文章主要介绍了Spring Boot(三)之找回熟悉的Controller,Service,需要的朋友可以参考下
    2017-04-04
  • Android读取本地或网络图片并转换为Bitmap

    Android读取本地或网络图片并转换为Bitmap

    这篇文章主要为大家详细介绍了Android读取本地或网络图片,并转换为Bitmap,感兴趣的小伙伴们可以参考一下
    2016-08-08
  • 什么是RESTful API,有什么作用

    什么是RESTful API,有什么作用

    提到RESTful API大家势必或多或少听说过,但是什么是RESTful API ?如何理解RESTful API 呢?今天咱们就来聊聊这个RESTful API
    2023-11-11
  • springboot整合flowable框架入门步骤

    springboot整合flowable框架入门步骤

    最近工作中有用到工作流的开发,引入了flowable工作流框架,在此记录一下springboot整合flowable工作流框架的过程,感兴趣的朋友一起看看吧
    2022-04-04
  • idea中cherry pick的用法

    idea中cherry pick的用法

    Cherry-Pick可以将一个分支的某些commit,合并到另一个分支,本文给大家分享idea中cherry pick的用法,感兴趣的朋友跟随小编一起看看吧
    2023-08-08
  • MultipartFile中transferTo(File file)的路径问题及解决

    MultipartFile中transferTo(File file)的路径问题及解决

    这篇文章主要介绍了MultipartFile中transferTo(File file)的路径问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Java责任链模式详解

    Java责任链模式详解

    责任链模式(Chain of Responsibility Pattern)是一种行为型设计模式,它用于将请求的发送者和接收者解耦,使得多个对象都有机会处理这个请求,本文将详细介绍 Java 中的责任链模式,包括其概念、结构、实现方式以及应用案例等,需要的朋友可以参考下
    2023-05-05
  • Java Maven settings.xml中私有仓库配置详解

    Java Maven settings.xml中私有仓库配置详解

    这篇文章主要介绍了详解Maven settings.xml配置,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-10-10

最新评论