Home > Back-end >  My function works good on debug, but not im main
My function works good on debug, but not im main

Time:04-22

I have to make a func that do somtheing like this 123 -> 321 with recursion When i see work of my func via debugger i see that a changed, but when i call function on main, nothing changed This is my code

#include <stdio.h>
#include <math.h>

long int SwapNum(long int , int);
int CountRoz(long int);

int main(){
    long int a = 123;
    printf("%ld", a);

    SwapNum(a, CountRoz(a));
    printf("%ld", a);

}
int CountRoz(long int a) {
    if (a / 10 == 0)
        return 1;
    return 1   CountRoz(a / 10);
}
long int SwapNum(long int a, int b) {
    
    a  =a % 10 * pow(10, 2 * b - 1);
    if (b == 1) {
        return 1;
    }
    b--;
    return SwapNum(a / 10, b);
}

Can you help me, because I cant find error

CodePudding user response:

You can also try passing by reference although I'm not sure your algorithm is exactly right.

long int SwapNum(long int *, int);
...
    SwapNum(&a, CountRoz(a));
...
long int SwapNum(long int *a, int b) {
    *a  = *a % 10 * pow(10, 2 * b - 1);
    if (b == 1) { return 1; }
    b--;
    long int a2 = *a/10;
    return SwapNum(&a2, b);
}

So, the modulus operator is probably what you're trying for in your first line in Swapnum. 123 % 10 yields the remainder of 123 divided by 10. And remember, integer math will yield integers; 12/10 yields 1.

Let's say we start with:

  • 123, 0
  • 123/10, 0*10 123 => 12, 3
  • 12/10, 3*10 12 => 1, 32
  • 1/10, 32*10 1 => 0, 321
  • 0, 321 => no more digits left from a, so 321 is our answer

    We traverse digits in A like you planned by dividing by 10 and
    also build up the return value by multiplying by 10 (plus remainder)
    long int SwapNum(long int, long int);
    
    int main(){
        long int a = 12388569;
        printf("%ld", a);
        printf("%ld", SwapNum(a,0));
    }
    long int SwapNum(long int a, long int b) {
        if (a == 0) return b;
        return SwapNum(a/10, b*10   a);
    }
    

    Hope this helps!
    Ron.

    • Related