簡體   English   中英

嘗試創建一個具有兩個長值的函數,並且僅當第一個值是第二個值的倍數時才返回true

[英]Trying to create a function that takes two long values and returns true if and only if the first value is a multiple of the second value

我很難理解為什么此功能行為不正確。

如果我將num1的值設為10,將num2的值設為20,則在運行時,程序會告訴我10等於20,而實際上卻不是。 當我切換數值並使num1 20和num2 10改變時,它告訴我num1是num2的倍數-這是正確的。

如果有人可以向我解釋我要去哪里哪里,並且他們可以向我顯示正確的代碼版本(如果可能),將不勝感激!

public class Multiple {

    public static void main(String[]args) {
        boolean multiple = true;

        while(multiple = true) {
            long num1 = 10;
            long num2 = 20;
            boolean result = isMultiple(num1, num2);

            if (result = true) {
                System.out.println(num1 + " is a multiple of " + num2);
            } else {
                System.out.println(num2 + " is not a multiple of " + num1);
            }
            break;
        }
    }

    public static boolean isMultiple(long x, long y) {
        if (x % y == 0) {
                return true;
        } else if (y % x == 0) {
            return false;
        }
        return false;
    }
}

您的代碼應類似於:

public static void main(String[] args) {
    boolean multiple = true;
    while(multiple) {
        long num1 = 10;
        long num2 = 20;
        boolean result = isMultiple(num1, num2);
        if(result){
            System.out.println(num1 + " is a multiple of " + num2);
        } else {
            System.out.println(num1 + " is not a multiple of " + num2);
        }
        break;
    }
}

public static boolean isMultiple(long x, long y){
    if (y%x == 0) {
        return true;
    }
    return false;
}

如果不需要,則更改= true。 同樣,為了使第一個數字是秒的倍數,您需要輸入第二個數字%第一個數字。 您不需要循環,但我認為您擁有循環,因為以后可能需要它,所以我保留了它。

if (result = true)實際上 result 設置true 應該將其更改為result == true 我不確定while循環的目的,但是我知道isMultiple方法肯定可以簡化。 無論如何,我更正了if條件並進行了其他一些重構。

public class Multiple {

    public static void main(String[] args) {

        long num1 = 10;
        long num2 = 20;

        if (isMultiple(num1, num2)) {
            System.out.println(num1 + " is a multiple of " + num2);
        } else {
            // num1 should come before num2 here
            System.out.println(num1 + " is not a multiple of " + num2);
        }
    }

    public static boolean isMultiple(long x, long y) {

        // check that x is a multiple of y
        return x % y == 0;
    }
}
public static void main(String[] args) {
    boolean multiple = true;
    while(multiple) {
        long num1 = 10;
        long num2 = 20;
        boolean result = isMultiple(num1, num2);
        if(result){
            System.out.println(num1 + " is a multiple of " + num2);
        } else {
            System.out.println(num1 + " is not a multiple of " + num2);
        }
        break;
    }
}

public static boolean isMultiple(long x, long y){
        if (x<y) return false;
        return (x % y == 0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM