Algorithm for printing reverse number set by user?

I wrote a small C ++ program that asks the user for input, the user gives the number, then the computer displays the number with the opposite sign.

For example: 17 becomes 71. 123 becomes 321.

This program:

#include <iostream>
#include <string>  //for later use.
using namespace std;

int rev(int x)
{
    int r = 0;
    while(x)
    {
        r = (r*10) + (x%10);
        x = x/10;
    }
    return r;
}

int main()
{
    int nr;
    cout << "Give a number: ";
    cin >> nr;
    rev(nr);
    cout << nr; 
    return 0;
}

The end result of the program: prints the same number, the function does not work. What am I doing wrong? I tried several solutions, but to no avail.

+3
source share
5 answers

You need to change rev(nr);tonr = rev(nr);

or alternately change your function to:

void rev(int& x)
{
    int r = 0;
    while(x)
    {
        r = (r*10) + (x%10);
        x = x/10;
    }
    x = r;
}
+7
source

You are doing it right, but you are not capturing your return value (the return value).

, :

cout << rev(nr);

nr = rev(nr);
cout << nr;
+4

, , , , , , :

std::string input;

std::cin >> input;

std::cout << std::string(input.rbegin(), input.rend());
+2

, rev. nr, rev, , rev .

:

int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result; 
return 0;
+1

STL std::reverse, .

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

int main() {

  long int i = 0;
  do {
    std::cout << "Gimme a number: " << std::endl;
  } while (not (std::cin >> i)); // make sure it *is* a number

  std::string display = std::to_string(i); // C++11

  std::reverse(display.begin(), display.end());

  std::cout << display << "\n";
}
+1

All Articles