如何计算没有“%”运算符的两个数字的余数/模?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何计算没有“%”运算符的两个数字的余数/模?相关的知识,希望对你有一定的参考价值。
例如,使用以下输入:
int num = -100
int divisor = 10
=> -100 mod 10 = 0 (Edge-case: negative numbers as input)
int num = 300
int divisor = -7
=>300 mod 7 = 6
我之前使用过这种方法,但是使用负数,它不起作用:
int method(int i, int div)
return (num - divisor * (num / divisor));
预期结果:
-1234, 512 ==> <302>
实际结果:
-1234, 512 ==> <210>
答案
以下测试证明您的初始实现提供了与原始%
运算符相同的结果:
static int mod(int n, int m)
return n - m * (n / m);
// test
int[][] data =
100, 10, -100, 10, 100, -10, -100, -10,
5, 3, - 5, 3, 5, - 3, - 5, - 3
;
Arrays.stream(data)
.forEach(d -> System.out.printf("%s: %d %% %d = %d mod=%d%n",
d[0]%d[1] == mod(d[0], d[1]) ? "OK" : "BAD",
d[0], d[1], d[0]%d[1], mod(d[0], d[1])));
输出:
OK: 100 % 10 = 0 mod=0
OK: -100 % 10 = 0 mod=0
OK: 100 % -10 = 0 mod=0
OK: -100 % -10 = 0 mod=0
OK: 5 % 3 = 2 mod=2
OK: -5 % 3 = -2 mod=-2
OK: 5 % -3 = 2 mod=2
OK: -5 % -3 = -2 mod=-2
另一答案
您的代码可以在没有模块的情况下正常运行。
它们对于负数和正数也给出相同的结果。
import java.util.*;
public class Main
public static void main(String[] args)
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Dividend : ");
int i = scan.nextInt();
System.out.println("\nEnter the Divisor : ");
int div = scan.nextInt();
System.out.println("Without modulo :Dividend: " + i + " , Divisor: " + div + ", Remainder: " +(i - div * (i / div)));
System.out.println("With modulo :Dividend: " + i + " , Divisor: " + div + ", Remainder: " +(i % div));
System.out.println("Using abstract :Dividend: " + i + " , Divisor: " + div + ", Remainder: " +Math.abs(i - div * (i / div)));
输出:
Enter the Dividend :
300
Enter the Divisor :
-7
Without modulo :Dividend: 300 , Divisor: -7, Remainder: 6
With module :Dividend: 300 , Divisor: -7, Remainder: 6
Using abstract :Dividend: 300, Divisor: -7, Remainder: 6
Enter the Dividend :
-1234
Enter the Divisor :
512
Without modulo :Dividend: -1234 , Divisor: 512, Remainder: -210
With module :Dividend: -1234 , Divisor: 512, Remainder: -210
Using abstract :Dividend: -1234 , Divisor: 512, Remainder: 210
另一答案
这是您的方法。
static int method(int num, int div)
return num - div * (num / div);
它可以正常工作,因为无论使用哪种符号,它都会返回余数%
。但是,如果您想要更多positive mod
答案,则需要执行以下操作:
static int method(int num, int div)
int mod = num - div * (num / div);
return (mod < 0) ? mod + div : mod;
从irem的Java Virtual Machine Specification开始。
value1和value2都必须为int类型。弹出值从操作数堆栈。 int结果为value1-(value1 / value2)*值2。结果被压入操作数堆栈。
以上是关于如何计算没有“%”运算符的两个数字的余数/模?的主要内容,如果未能解决你的问题,请参考以下文章