0
What should I do to only get the numbers that are divisible by 5 to print "Beep"?
This is from the No. 21 Code Project "Countdown" can someone tell me what is wrong. This is for c++ language My code: #include <iostream> using namespace std; int main() { int n; cin >> n; //your code goes here for(int x = n; x > 0; x--) { cout << x << endl; if(x%5) { cout << "Beep" << endl; } } return 0; }
2 Answers
+ 1
x modulo 5 (x%5) is the remainder when x is divided by 5. For instance if x is 11, then x%5 is 1, because 10 is divisible by 5, so the remainder for 11 is 1. Therefore to check if a number x is divisible by 5, you need to check that the remainder is 0 when it is divided by 5. But you are not doing that in your if statement, instead you have: if(x%5). If x is 6, your if statement will evaluate to 1 ( since 6%5 is 1).
Can you figure out what to do?
+ 1
Thank for the reply. Actually, I already got the right code. I just added the NOT operator in my If(! (x%5)) to print the word Beep