Codeur
Codeur

Reputation:

My 'cout' isn't giving correct value - why?

Simple "sum of digits" code. It compiles but when executed, the last cout gives a "0" for the num int rather than the actual user-input number.

Feel free to copy and paste this into your own compiler, if you're so inclined, to see what I mean.

How can I get this to output the correct "num" value?

~~~

#include <iostream>

using namespace std;

int main()
{
  int num;
  int sum = 0;

  cout << "Please type any non-negative integer: ";
  cin >> num;

  while ( num > 0 ) {
    sum += num % 10;
    num /= 10;
  }

  cout << "The sum of the digits of " << num << " is " << sum << "\n";

  system("PAUSE");
  return 0;
}

Upvotes: 0

Views: 351

Answers (3)

Johannes
Johannes

Reputation: 23

For the next time, you can try to use a debugger. You'll find those "bugs" very easy!

Upvotes: 1

clahey
clahey

Reputation: 4843

The problem is that num /= 10 changes num. If you want to get this to work, you should create a temp variable that you use to do all the calculations.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881477

You've been modifying num all along until it becomes 0 (that's what your while ( num > 0 ) statement ensures!), so OF COURSE it's 0 at the end! If you want to emit what it was before, add e.g. int orig=num; before the loop, and emit orig at the end.

Upvotes: 11

Related Questions