[英]How do I calculate the rest/modulo of two numbers without the “%” operator?
例如使用以下輸入:
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])));
Output:
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)));
}
}
Output:
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虛擬機規范。
value1 和 value2 都必須是 int 類型。 這些值從操作數堆棧中彈出。 int 結果是 value1 - (value1 / value2) * value2。 結果被壓入操作數堆棧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.