How to correctly call a function through another function in C?

Asked

Viewed 2,117 times

1

I have the following duties :

int testarDivisibilidade(int dividendo, int divisor);
int divisibilidade3(int num);

And the following variables: :

int dividendo;
int divisor;

With the function testarDivisibilidade, I’ll check if the dividendo is divisible by the divisor.

Code :

int divisibilidade3(int num)
{
    int res = 0;

    while( num > 0 )
    {
        res += num % 10;
        num /= 10;
    }

    if(res > 9)
        return divisibilidade3(res);
    else
        return ! (res % 3);

int testarDivisibilidade(int dividendo,int divisor) {

    if(divisibilidade3(dividendo) == 1) {
        printf("%d é divisivel por %d ", dividendo,divisor);
        return 1;
    }

    return 0;


}

I have to check if divisibilidade3returns true to be able to fire the message inside the if. But this giving problem, because for all cases of the dividendo, he returns as true.

Summarizing : How can I correctly check my function divisibilidade3 within the function testarDivisibilidade ?

1 answer

2


I note that the example code you posted does not compile:

  • First, on line 12, you’re calling a function Divisibilidade(), when you certainly wanted to call divisibilidade3() (note the D capital and the lack of 3).

  • Second, on the same line 12, you are calling the function and discarding the result: what you effectively meant is return divisibilidade3(res); This causes the compiler to issue an error that "not all code paths return".

  • Finally, in the base case of the recursion, on line 14, you are returning res % 3, that does not return 1 when num is divisible by 3. Instead, you mean return res % 3 == 0; or return ! (res % 3);

With these changes, the divisibilidade3() inside testarDivisibilidade() is correct and should work.

Note that in the function testarDivisibilidade(), you test yourself dividendo is divisible by 3 using divisibilidade3() and, being, sends a message saying that dividendo is divisible by divisor, for any value of divisor! Strictly, this is wrong unless you pass 3 as argument for the parameter divisor.

  • Wow, thank you very much, it worked correctly. In fact it will only call divisibility function3 if the user chooses divisor 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.