简体   繁体   English

从循环内部更新循环外部的变量

[英]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.尝试创建一种方法来返回“n”以下的第一个数字,该数字可以完全除以第一个和第二个除数。 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.目前我的程序返回“答案”的默认值为 0,我希望在循环内计算的值在循环外被转换返回。 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.尝试创建一种方法来返回“n”以下的第一个数字,该数字可以完全除以第一个和第二个除数。

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.将计数器从n减少到 1。但是,除非余数为零,否则您的answer不会更新。 If that condition is never met, the default value of n will be returned (which is zero).如果从未满足该条件,则将返回n的默认值(为零)。

The problem?问题? remainder = multipliedDivisors / i when will remainder be zero? remainder = multipliedDivisors / i remainder何时为零?
Because of this assignment, int multipliedDivisors = firstDivisor * secondDivisor;因为这个赋值, int multipliedDivisors = firstDivisor * secondDivisor; , only if one of the "divisor" variables is zero. ,仅当“除数”变量之一为零时。

Redo your logic.重做你的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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