【问题标题】:Why is this variable being assigned 0 even after dividing and being initialized? [duplicate]为什么这个变量在除法和初始化后仍被赋值为 0? [复制]
【发布时间】:2021-07-30 12:17:57
【问题描述】:

下面是我的代码-

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;
        }

buySumnoOfIndicators 的值分别为 1 和 3。如您所见,divBuy 也已正确初始化并且不是空值。尽管如此,在divBuy = buySum / noOfIndicators 行通过后,1/3 并没有分配给divBuy,并且值仍然为0。为什么会发生这种情况?

如果过去曾多次问过此问题,我们深表歉意。提前致谢

【问题讨论】:

标签: c# for-loop


【解决方案1】:

double divBuy = buySum / noOfBuyIndicators;

buySumnoOfBuyIndicators 都是整数时,除法将是整数除法。

含义:1 / 3 == 0

修复很简单:

  divBuy = (double)buySum / noOfBuyIndicators;

【讨论】:

  • divBuy 也应该是 decimal,考虑到财务状况。
  • 是的,但这是一个单独的问题。 double 可以解决很多财务问题。
猜你喜欢
  • 2019-12-23
  • 2020-12-06
  • 1970-01-01
  • 2016-04-02
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
相关资源
最近更新 更多