Incorrect count in ASP.NET View

Viewed 80

I wrote special formula for calculating percentages, but it does not calculate correctly. I have phone.Sale and phone.Repair. Sale is the number of sales and Repair is the number of repairs. Ratio means the reliability.

For instance, 697 sales and 231 repairs. It should be 33 (100 - 100/697*231), but it shows 100. How to fix it? phone.Sale, phone.Repair and phone.Ratio have "int" type.

    <div>
        @foreach (var phone in Model.Phones)
        {
            phone.Ratio = 100 - 100 / phone.Sale * phone.Repair;
            <div class="smartphone">
                <p>Smartphone - @phone.Name</p>
                <p>Number of sales — @phone.Sale, number of repairs — @phone.Repair</p>
                <p>Reliability index — @phone.Ratio %</p>
            </div>
        }
    </div>
1 Answers

You should use parentheses, (), to change the order of evaluation imposed by operator precedence and associativity.

As an example:

Console.WriteLine(2 + 2 * 2);   // output: 6
Console.WriteLine((2 + 2) * 2); // output: 8

Console.WriteLine(9 / 5 / 2);   // output: 0
Console.WriteLine(9 / (5 / 2)); // output: 4

So update calculation with the following line:

phone.Ratio = 100 - (100 / phone.Sale * phone.Repair);

For more information check Operator precedence And Arithmetic operators (C# reference)

Related