简体   繁体   中英

C# A loop using while. Variable displayed only once

I have a small problem. My code is this one :

int c = 0;
int i = 0;
int a = 28;
while (i < a) {
    i++;
    if (i % a == 0) {
        c += i;
        Console.WriteLine(i.ToString());
    }
}

Why does the string i is displayed only once, after the end of the while ? It should be displayed a times.

Your help will be appreciated !

Your if condition is opposite it should be:

 if (a % i == 0)

Currently you are trying to do remainder division with i % a and it will only meet the condition when i reaches 28 , so you get the output once.

% is for modulus division, which basically divides by the number and gives you back the remainder. When you're loop reaches 28 it divides it by 28 and the resulting remainder is 0. This only happens once "when your loop reaches 28".

It would help if you told us what was printed out. I guess it is 28 because

i % a

returns the reminder of

i / a

(i divided by a) and it is only 0 when i is equal to a, ie, 28.

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