Question

Sorry if I don't explain this as well as I should... I've written the code below in a console main.

int myint = 0;
while (myint < 100) {
    myint++;
    if ((myint / 16) == 0) {
        Console.WriteLine(myint); }
}

Now what I wan't is for it to post multiples of 16 so I changed the ((myint / 16) == 0) to ((myint % 16) ==0) which worked... My actual question is, when I use ((myint / 16) == 0) why does it write 1-15 to the console?

Was it helpful?

Solution

Because

(myint / 16) == 0

is only true if myint is smaller than 16. So, e.g. 5 / 16 is 0 beacuse you are dividing integers (result is rounded down).

Also, the output starts with 1 since you do

myint++ 

before the if / Console.WriteLine and you have myint initialized with 0.

OTHER TIPS

Because you're performing Integer division. Whatever number less than 16 (myint / 16) will yield zero as result which evaluates to true so it prints from 1-15.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top