Exit a method call cycle

Asked

Viewed 64 times

0

Let’s imagine the following situation:

A company has the policy of donating 3% of its profit to social projects, and this amount donated should come as an expense to the company in the period.

Briefly we have this situation:

Descrição do problema

Mounting in Excel would be this and it is possible to solve:

Como fica no Excel

To facilitate the cycle, let’s assume that the revenue is 10,000.00 and the only expense that exists for the company is with the donation.

Turning the situation into code:

double calculaDoacao() { return 0.03 * calculaLucro(); }
double calculaLucro() { return 10000 - calculaDoacao();}

How to solve this problem, since this cycle is necessary?

Troubleshooting reference in Excel.

  • 1

    Set "returns". Show the code. In your problem you have to have a shutdown condition, if you don’t have it is impossible to solve this.

  • Okay. I’ll edit the problem to be clear.

  • Revenue - Expenses = Earnings_antes_donation. Lucro_real = Lucro_antes_donation - Donation.

1 answer

0


First, you’re using the wrong type for monetary value, see the problem. And What is the correct way to use the float, double and decimal types?.

Read everything on the page linked? It shows how to configure Excel and shows that after turning on the cyclic reference break you also have to say how many iterations you want to be performed. That is, it has established a condition of ending the repetition of calls, so the code has to deal with it. Is that what you want? I made an example, I would do it in a better way, but I didn’t want to change too much what you’re trying to do.

using static System.Console;

public class Program {
    public static void Main() {
        var x = new Exemplo();
        WriteLine(x.CalculaLucro());
    }
}

public class Exemplo {
    private decimal calculaDoacao(int iteracao, decimal valor) => 0.03M * calculaLucro(iteracao, valor);
    private decimal calculaLucro(int iteracao, decimal valor) {
        if (iteracao++ == 100) return valor;
        return valor - calculaDoacao(iteracao, valor);
    }
    public decimal CalculaDoacao() => calculaDoacao(0, 10000M);
    public decimal CalculaLucro() => calculaLucro(0, 10000M);
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

At a certain point the number of interactions does not change the useful end result. That is, with 100 or with 10 the value after 2 or 4 decimal places, as we usually use in monetary values, the value is the same. In this case with 5 seems to be enough.

Browser other questions tagged

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