I'm a somewhat-more-than-beginner to C++ and programming. I'm working on writing a function that will take an integer and reverse its digits, e.g. reverseDigit(2376) = 6732. I have run into a problem that I absolutely cannot understand, though I have spent hours working with the code, tracing it, printing out results to track what it's doing.
The problem is that the function inexplicably (to me) works differently for ints with odd numbers of digits than for ints with even numbers of digits. However, if I print the result of each step along the way, I see no difference in what the code is doing at any step.
Here is the code for the function:
void reverseDigit(int num)
{
int digCount = digitCount(num);
int flippedNum = 0;
for (int i = 1; i <= digCount; i++)
{
cout << "Run #" << i << ": " << endl;
cout << "((num % 10)*pow(10, digCount - i)) = " << ((num % 10)*pow(10, digCount - i)) << endl;
cout << "num = " << num << ", flippedNum = " << flippedNum << endl;
flippedNum += ((num % 10)*pow(10, digCount - i));
num = num / 10;
}
cout << "The new number is " << flippedNum << endl;
}
And here are the results I get for an even int and then an odd int (with intermediate results printed):
So you see what is going wrong here: when I enter 256 (or any int with odd number of digits), somehow flippedNum gets decremented by 1. I cannot for the life of me find where in the code I have told the computer to do this! flippedNum is initialized to 0, and the value I add to it is equal to 600, yet somehow flippedNum gets the value 599!