2011-11-24 93 views
21

我正在使用AndEngine将精灵添加到屏幕,并使用movemodifier方法。如何检查数字是否可以被某个数字整除?

我有两个整数 MaxDuration和MinDuration;

我想要做的是当用户得到某个增量的分数。

像例如..当用户到达20(整数变化)时,当用户到40(整数变化)。所以基本上按20计数,并且每次得分满足整数变化整除的数字。我希望这是有道理的。

有没有什么方法可以做到这一点?我有一个UpdateTime处理程序,可以每秒钟检查分数。

任何想法?

回答

66
n % x == 0 

意味着n可以除以x。所以...例如,你的情况:

boolean isDivisibleBy20 = number % 20 == 0; 

另外,如果你想检查一个数是否为偶数或奇数(无论它是由2个或不能整除),你可以使用位运算符:

boolean even = (number & 1) == 0; 
boolean odd = (number & 1) != 0; 
+8

要添加到这一点,本symbole(%)是被称为*模量*运算符,或简称* MOD *。所以这个函数可以读为* n mod x等于0 *。 – Phil

+0

因此,在这种情况下,如果得分是20,并且它检查它是否可以被20整除,那么答案将是1.所以这将是错误的?正确?为什么它== 0? –

+0

正确。它会返回正确的剩余部分? –

3
package lecture3; 

import java.util.Scanner; 

public class divisibleBy2and5 { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     System.out.println("Enter an integer number:"); 
     Scanner input = new Scanner(System.in); 
     int x; 
     x = input.nextInt(); 
     if (x % 2==0){ 
      System.out.println("The integer number you entered is divisible by 2"); 
     } 
     else{ 
      System.out.println("The integer number you entered is not divisible by 2"); 
      if(x % 5==0){ 
       System.out.println("The integer number you entered is divisible by 5"); 
      } 
      else{ 
       System.out.println("The interger number you entered is not divisible by 5"); 
      } 
     } 

    } 
} 
相关问题