#include <iostream>
using std::cin; using std::cout; using std::endl;
int reverse(int n);
int main()
{
int number;
cout << "Enter a number between 1 and 9999: "; cin >> number;
cout << "The number with its digits reversed is: ";
cout << reverse << endl; //insert calling statement to FUNCTION
return 0; // 0 indicates successful termination
return 0;
}// end main
// reverseDigits returns number obtained by reversing digits of n
int reverse(int n)
{
int reverse = 0;
int divisor = 1000;
int multiplier = 1;
//n, below, is reduced step by step until it becomes less than 9
while (n > 9) //loop until we get a single digit
{
if (n >= divisor) // if n >= current divisor, determine digit
{
reverse += n / divisor * multiplier; // update reversed number with current digit
n %= divisor; // n stores the remainder of n/divisor
divisor / 10; //divide divisor by 10
multiplier * 10; //multiply multiplier by 10
}
else
divisor /= 10; //divide divisor by 10
} // ENDWHILE
reverse += n * multiplier; //reverse gets newest digit tacked on
return reverse; // return reversed number
} // ENDFUNCTION
Ok, so this is the code I have written so far. The object of the code is to input a number, and call the function to reverse that number and output it. I can't seem to get my values to pass back and forth successfully. The code does compile, but the output is completely wrong. Any help or direction would be great. Thank you.
#include <iostream>
using std::cin; using std::cout; using std::endl;
int reverse(int n);
int main()
{
int number;
cout << "Enter a number between 1 and 9999: "; cin >> number;
cout << "The number with its digits reversed is: ";
cout << reverse << endl; //insert calling statement to FUNCTION
return 0; // 0 indicates successful termination
return 0;
}// end main
// reverseDigits returns number obtained by reversing digits of n
int reverse(int n)
{
int reverse = 0;
int divisor = 1000;
int multiplier = 1;
//n, below, is reduced step by step until it becomes less than 9
while (n > 9) //loop until we get a single digit
{
if (n >= divisor) // if n >= current divisor, determine digit
{
reverse += n / divisor * multiplier; // update reversed number with current digit
n %= divisor; // n stores the remainder of n/divisor
divisor / 10; //divide divisor by 10
multiplier * 10; //multiply multiplier by 10
}
else
divisor /= 10; //divide divisor by 10
} // ENDWHILE
reverse += n * multiplier; //reverse gets newest digit tacked on
return reverse; // return reversed number
} // ENDFUNCTION
First of all, line 11 is printing the address of the function, you're not even calling it. You need to call the function with the argument it's expecting: reverse(number)
You're returning from main twice - the compiler will magic it away for you, but why have it there at all?
Your whole reverse function doesn't make sense to me. Typically, when I need to tamper with numbers like this I convert them to strings and do whatever I want with them. Reversing a string is much easier.