2011-09-23 59 views
0

因此,對於這個問題,這個問題問如何確定一個整數是否可以被另一個整數所整除?

一個數字x是由y整除,如果該餘數是零。編寫一個程序,測試一個數字是否可以被另一個數字整除。從鍵盤上讀取兩個數字。

這是我迄今爲止

import java.util.Scanner; 

public class ch3ProblemOne 
{ 

public static void main(String[] args) 
{ 

    int x; 
    int y; 
    Scanner keyboard = new Scanner(System.in); 
    x = keyboard.nextInt(); 
    y = keyboard.nextInt(); 

    if (x == 5); 
    else if (y <= 0); 
    System.out.println(x + "is not divisible by" + y); 

    else if (x == y); 

    System.out.println(x + "is divisible by" + y); 
+1

不要忘記整數總是向下舍入。 5/2 = 2,而不是2.5。 – ben

+0

正如Ben所說,您可以使用整數除法截斷的事實,而不是使用模數運算符(%)。如果5/2 = 2,那麼2 * 2 = 4,4!= 5 - >所以5不會被2除。 –

回答

1

使用modulooperator,它返回從除法運算的餘數。

public class ch3ProblemOne { 

public static void main(String[] args) 
{ 
    Scanner keyboard = new Scanner(System.in); 
    int x = keyboard.nextInt(); 
    int y = keyboard.nextInt(); 

    if ((x % y) == 0) { System.out.println(x + " is divisible by " + y); } 
    else { System.out.println(x + " is not divisible by " + y); } 
    } 
} 
+2

作業答案的代碼太多。給提示,而不是盆栽答案。 –

10

您需要使用模數運算符,該運算符告訴餘數是多少。

等你的變量

10 % 2 == 0 

10 % 7 == 3 

使用%

+0

但請務必不要模擬零! – templatetypedef

+0

...或處理ArithmeticException,如果您除以零,則返回結果。 (我不會說哪種方法更好,OP最終需要了解如何處理異常...以及何時防止它們首先發生,但這些是「更高級」的主題。 ) –

相關問題