Need help reversing a number (Can't get the right answer)

I don't get the right answer. I hope I don't need to translate the whole code in English. All I need to do is make a number for example 45 to 54 or 79 to 97. You can see my function below. The thing is I don't get the right answer. I tried typing counting x, sk and it reads the file correctly. If there are questions and you need translation, leave a comment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>
using namespace std;
//
const char duom [] = "skaiciai.txt";
const char rez [] = "atsakymas.txt";
//
int SkaicApv(int Apverstas, int sk, int s);
//
int main()
{
    ifstream iv(duom);
    ofstream is(rez);
    int sk, x, SkaicApv1, s, Apverstas;
    iv >> x;
    for (int i = 1; i <= x; i++){
        iv >> sk;
        SkaicApv1 = SkaicApv(Apverstas, sk, s);
        Apverstas = SkaicApv1;
        is << "Apverstas skaicius bus: " << SkaicApv1 << endl;

    }
    return 0;
}
//
int SkaicApv(int Apverstas, int sk, int s){
while (sk < 0){
    s = sk / 10;
    sk = sk % 10;
    Apverstas += sk * 10 + s;
}
return Apverstas;
}
You can read it in as a string, and just reverse it with the std algorithm function reverse.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>
#include <algorithm>
using namespace std;

int main()
{
   string x;
   cin >> x;
   reverse(x.begin(), x.end());
   cout << x;
   
   return 0;
}

We are not learning string yet. There has to be way without it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
   int x, remainder, reversedNumber;
   reversedNumber = 0;
   cin >> x;

    while(x != 0)
    {
        remainder = x%10;
        reversedNumber = reversedNumber * 10 + remainder;
        x /= 10;
    }

   cout << reversedNumber;
   
   return 0;
}
In your code, what is the starting value of Apverstas ? Is it meant to be zero? If you want it to start at zero, you need to set it to zero.
Topic archived. No new replies allowed.