2012-02-08 37 views

回答

24

%确实在Java中求余运算。

要得到适当的弹性模量,可以使用剩余的功能:

它使用三元操作做标志修正最短:

private int mod(int x, int y) 
{ 
    int result = x % y; 
    return result < 0? result + y : result; 
} 

对于那些谁不喜欢三元运算符,这是等效的:

private int mod(int x, int y) 
{ 
    int result = x % y; 
    if (result < 0) 
     result += y; 
    return result; 
} 
+0

谢谢唐,它的工作原理。 – 2012-02-08 22:47:15

+0

@don roby:这个操作符意味着什么:返回结果<0?结果+ y:结果;谢谢 – Kenji 2014-02-26 12:22:21

+0

@Kenji - 请参阅[wikipedia on ternary operator?:](http://en.wikipedia.org/wiki/%3F :) – 2014-02-26 12:47:35

8

因为如果您将-2除以6,则会得到-2作为余数。 %运算符将会像下面一样给出余数;

int remainder = 7 % 3; // will give 1 
int remainder2 = 6 % 2; // will give 0 

要得到模:

// gives m (mod n) 
public int modulo(int m, int n){ 
    int mod = m % n ; 
    return (mod < 0) ? mod + n : mod; 
} 
+0

好的,但是我怎样才能在Android中获得mod? – 2012-02-08 22:42:07