Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Recently I tried to write a program that prints out LCM of the two numbers put in parameter. And although I fortunately do not have any compile errors, I am not getting the right answer. I used nested ifs in for loop and I couldn't find the problem...can you help me? I am in overall confused by i++ concept. Thank you.

Here is what I wrote for my LCM class.

public class LCM {
    public static int calcLCM(int num1, int num2) { // num1=10, num2=4; their
                                                    // LCM is 20
        // num1 has to be greator than num2
        int multiple = 0;
        for (int i = 1; i == num1; i++) {
            if (num2 == num1) {
                multiple = num2;
            }

            else if (num2 * i > num1) {
                i++;
                num1 = num1 * i;
            }

            else if (num2 * i < num1) {
                i++;
                num2 = num2 * i;
            }

        }
        return multiple;
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

Change for(int i=1;i==num1;i++) to for(int i=1;i<=num1;i++).

The for loop in your current code runs only if i == num1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...