E
E
extowgen2015-12-23 17:17:39
Programming
extowgen, 2015-12-23 17:17:39

Why doesn't the code (C++) work?

should display numbers that are divisible by 2, but not divisible by 4. But in the end, on the contrary: it displays only those that are divisible by 4,
the essence:

for(x=0;x<100;x=x+2)
{
    if(x%4) continue;
    cout<<x;
}

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vladimir Martyanov, 2015-12-23
@vilgeforce

if(x%4) continue; What do you think it does? And, in particular, what would 5%4 be?

A
Alexander Movchan, 2015-12-23
@Alexander1705

It is possible like this:

for(int x = 0; x < 100; x = x + 2)
{
    if(x % 4) cout << x;
}

Or like this:
for(int x = 0; x < 100; x = x + 2)
{
    if(x % 4 == 0) continue;
    cout << x;
}

The bottom line is that in the condition zero is cast to false, and any other number to true.
Well, in general, there is a better way:
for(int x = 2; x <= 100; x += 4)
{
    cout << x;
}

T
Therapyx, 2015-12-23
@Therapyx

int main() {
  int x;
  cin >> x;
  if (x % 2 == 0 && x % 4 != 0) {
    cout << x << endl;
  }
}

% - calculates the remainder, for example 13% 2. 13 will fit 6 times 2 = 12. total 1 remainder. Duck, this remainder is the result after the operation with%. Any even number will have a remainder of 0 when divided by 2, but not all numbers are divisible by 4, so x % 2 == 0 "AND" x % 4 != 0

S
slinkinone, 2015-12-23
@slinkinone

if(x%4 != 0 && x%2 == 0)
    cout<<x;
else continue;

S
SuperHamster, 2015-12-23
@SuperHamster

For the code to work correctly, it is enough just to invert the condition, because 0 in C++ is false, and all non-zero values ​​are true.

for (x = 0; x < 100; x = x + 2)
{
    if ( !(x % 4) ) continue;
    cout << x;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question