开发者

Reverse numeral input

I'm trying to get my code to print out the reverse of whatever integer is input. No errors, ju开发者_运维百科st not printing out correctly. What am I doing wrong?

#include<iostream>
#include<conio.h>

using namespace std;

int num, n;
int reverse(int);

int main()
{
    cout << "Enter a number less than 1000 to be reversed:" << endl;
    cin >> num;
    reverse(num);
    cout << "reversed number is:";
    getch();
    return 0;
}

int reverse(int num)
{
    long sum=0;int rem;

    while(n>0)
    {
        rem=n%10;
        sum=sum*10+rem;
        n=n/10;
        cout << sum << endl;
    }

    return sum;
    cout << sum << endl;
}


n is uninitialized in your program, yet you're using it in the while loop.

Try this:

int reverse(int num)
{
   int sum=0;
   while(num>0)
   {
     sum=sum*10+ num %10; 
     num=num/10;
   }
   return sum;
}

And since this function returns an integer which is reverse of the number which you passed to the function, you have to save the returned value, at the call-site as:

int revnum = reverse(num); //in your code, you're not doing this.

Now see the complete online demo : http://ideone.com/hLnS1

By the way, avoid global variables:

 int num, n; //avoid declaring these at global level.

Define them at local scope, as I did in the demo (see it).


Reversing a number is easier if you treat it as a string.

e.g.

#include <iostream>
#include <string>
#include <algorithm> 

int main()
{
    std::string sNum;

    std::cout << "Enter a number:" << std::flush;
    std::cin >> sNum;
    std::reverse(sNum.begin(), sNum.end());
    std::cout << "\nThe reverse is \"" << sNum << "\"";
    std::cout << "\n\nPress return to finish" << std::endl;
    std::cin.get();
    return 0;
}

Produces

Enter a number:123456789

The reverse is "987654321"

Press return to finish
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜