Program runs but does not output desired results

I need to get this program to ignore even numbers and only add positive ODD numbers. The loop is designed to end when the user inputs "-1" and this feature works. The problem I am having is my code doesn't print the show the results of the addition, or when I can get the program to print the results out the number I am getting back is WRONG.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
  int in;
  int total = 0;

  while (true) {
    cout << "Enter a positive odd number or -1 to get quit ";
    cin >> in;
    if (in <= 0) {
      break;
    } else if (in % 2 == 0) {
      total += in;
      cout << total;
      cout << " The total number of odd intergers equals = " << total + in << endl;
    }
  }
}
Last edited on
look at line 14 more closely and ask yourself what it is doing.

Remember that % gives you remainder after division. So if in % 2 gives you zero, what does that tell you about 'in'?

Also, you summed 'in' on line 15, so why are you adding it again on line 17?
I have been working on this but still can't get it add the numbers right.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  int in;
  int total = 0;

  while (true) {
    cout << "Enter a positive odd number or -1 to get quit ";
    cout << "\n";
    cin >> in;
    if (in <= 0) {
      break;
    } else if (!in / 2 == 0) {
      total = total + in;
      total++;
      cout << "The total number of odd intergers equals = " << total  << endl;
    }
  }
}
You were closer with your first attempt.

else if (!in / 2 == 0) { <-- I don't know what you were trying to do here, but that's all wrong.


else if (in % 2 == 0) { <-- this is very close.

Remember how the % operator works. It gives you the remainder after division.

So...

0 % 2 == 0  (0 / 2 is 0 remainder 0)
1 % 2 == 1  (1 / 2 is 0r1)
2 % 2 == 0  (2 / 2 is 1r0)
3 % 2 == 1  (3 / 2 is 1r1)


So with that in mind.... if you are doing if (in % 2 == 0), what are you actually checking for?



Also, why are you incrementing the total on line 12?
So with that in mind.... if you are doing if (in % 2 == 0), what are you actually checking for?

I am trying and failing to make the program ignore even numbers



Also, why are you incrementing the total on line 12?

I thought I needed to increment it so it would do a running total of all odd numbers.
Topic archived. No new replies allowed.