Variable keeps zeroed in a mathematical expression

Asked

Viewed 61 times

1

My little show is like this:

        public void CalculaProporção()
    {
        decimal contagemSubida = 0 , contagemDescida = 0;
        int cSubida = 6, cDescida = 4, range = 10;
        contagemSubida += Convert.ToDecimal(cSubida*range/100);
        contagemDescida += Convert.ToDecimal(cDescida*range/100);

        contagemSubida = contagemSubida + Convert.ToDecimal(contagemSubida * (4/10));
        contagemDescida = contagemDescida + Convert.ToDecimal(contagemDescida * (4/10));
    }

My countdown variablesSubida and countsDescida have the value 0 throughout the procedure, what should I do for them to calculate correctly?

2 answers

2


You’re making an unnecessary conversion and too late. When you make a division with integers, you will have the result as an integer, and the integer of the obtained result is 0. If you want the decimal part you need to use a given decimal, be it for a variable that is already decimal or a literal of that number. The literal of the type decimal always accompanied by the suffix M of money, since this type is usually used for monetary value. Without the suffix is by default an integer, and there is problem. Thus should give the expected result:

using static System.Console;

public class Program {
    public static void Main() {
        decimal contagemSubida = 0 , contagemDescida = 0;
        int cSubida = 6, cDescida = 4, range = 10;
        contagemSubida += cSubida * range / 100M;
        contagemDescida += cDescida * range / 100M;
        contagemSubida += contagemSubida * (4 / 10M);
        contagemDescida += contagemDescida * (4 / 10M);
        WriteLine(contagemSubida);
        WriteLine(contagemDescida);
    }
}

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

Note that if you change the type of the secondary variables to decimal the result can be another without changing the divisor to the type decimal and it doesn’t seem to be what you want, although I can’t say because the question doesn’t say what the outcome should be.

  • Perfect! I understood the line of reasoning, applied and gave right :D

1

I don’t know if it was your broker but you don’t usually use accentuation in programming.

Change data type to decimal:

decimal cSubida = 6, cDescida = 4, range = 10;

Example: https://dotnetfiddle.net/clVoHU

  • 1

    As the above solution, this model also worked perfectly, thanks for the help :D

Browser other questions tagged

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