简体   繁体   中英

Update a variable outside a loop from inside the loop

Trying to create a method to return the first number below "n" which can be entirely divided by both the first and second divisor. Currently my program is returning the default value of "answer" being 0, I want the value which is calculated within the loop to be translated outside the loop to be returned. Yes I am a beginner:(

static int highestNumberBelowNDivisibleByTwoNumbers(int firstDivisor, int secondDivisor, int n) {
    int multipliedDivisors = firstDivisor * secondDivisor;
    int answer = 0;
    int remainder = 0;
    for (int i = n; i <= 1; i--) {
        remainder = multipliedDivisors / i;
        if (remainder == 0){
            answer = i;
            break;
        }
    }
    return answer;      
}

Based on your description of:

Trying to create a method to return the first number below "n" which can be entirely divided by both the first and second divisor.

Try something more like below with the % operator (remainder/modulo):

static int highestNumberBelowNDivisibleByTwoNumbers(int firstDivisor, int secondDivisor, int n) {
    while (n>0) {
        if ((n % firstDivisor == 0) && (n % secondDivisor == 0)) {
            return n;
        }
        n--;
    }
    return -1; // no answer found      
}

Your code

for (int i = n; i <= 1; i--) {
    remainder = multipliedDivisors / i;
    if (remainder == 0){
        answer = i;
        break;
    }

Decreases the counter from n down to 1. HOWEVER, your answer is not updated UNLESS remainder equals to zero. If that condition is never met, the default value of n will be returned (which is zero).

The problem? remainder = multipliedDivisors / i when will remainder be zero?
Because of this assignment, int multipliedDivisors = firstDivisor * secondDivisor; , only if one of the "divisor" variables is zero.

Redo your logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM