0

Here is my code below-

double divBuy = 0;
for (int j = 0; j < equityCheckArray.Count; j++)
        {
            for (int i = 0; i < noOfBuyIndicators; i++)
            {
                buySum += buySignal[i][j];
            }
            divBuy = buySum / noOfBuyIndicators;
            averageBuy[j] = divBuy;
        }

buySum and noOfIndicators both have values assigned to them as 1 and 3 respectively. As you can see, divBuy is also initialized correctly and is not a null value. Still, after divBuy = buySum / noOfIndicators line is passed, 1/3 is not assigned to divBuy and the value remains as 0. Why is this happening?

Apologies if this question has been asked multiple times in the past. Thanks in advance

ameyashete
  • 27
  • 6
  • What are the types of the variables being used? Is the `for` loop being entered at all? Can you provide a [mcve] which fully demonstrates the problem? – David Jul 30 '21 at 12:20
  • 2
    Are `buySum` and `noOfBuyIndicators` both `int` by any chance? https://stackoverflow.com/questions/10851273/why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float – Matthew Watson Jul 30 '21 at 12:20

1 Answers1

1

double divBuy = buySum / noOfBuyIndicators;

When buySum and noOfBuyIndicators are both integers then the division will be an integer division.

Meaning: 1 / 3 == 0.

The fix is simple:

  divBuy = (double)buySum / noOfBuyIndicators;
H H
  • 263,252
  • 30
  • 330
  • 514