为什么变量总是为零

时间:2016-09-05 04:44:50

标签: c# linq

我发现了一件非常奇怪的事情:

var PerformanceSingleList = TradePositionList//Compute the data for each stock everyday
            .SelectMany((o, idx) => o.Select(p =>
            {
                //default variable
                double CloseYesterday = TradePositionList.ElementAt(0).Where(q => q.Stock.Symbol == p.Stock.Symbol).Select(q => (double)q.Stock.Close).First();
                int PositionYesterday = TradePositionList.ElementAt(0).Where(q => q.Stock.Symbol == p.Stock.Symbol).Select(q => q.Position).First();
                int TradePositionToday = 0;
                if (idx != 0) //idx cann't be 0 otherwise, idx - 1 throw a error
                {
                    PositionYesterday = TradePositionList.ElementAt(idx - 1).Where(q => q.Stock.Symbol == p.Stock.Symbol).Select(q => q.Position).First(); 
                    CloseYesterday = TradePositionList.ElementAt(idx - 1).Where(q => q.Stock.Symbol == p.Stock.Symbol).Select(q => (double)q.Stock.Close).First();
                    TradePositionToday = TradePositionList.ElementAt(idx - 1).Where(q => q.Stock.Symbol == p.Stock.Symbol).Select(q => q.RealDesignTradeShare).First();                        
                }

                double Commission = Math.Abs(TradePositionToday) * (double)p.Stock.Close * C;


                return new
                {
                    p.Stock,
                    p.Position,
                    p.RealDesignPosition,
                    p.RealDesignTradeShare,
                    TradePositionToday,
                    Commission,
                    PLN = ((double)p.Stock.Close - CloseYesterday) * PositionYesterday + TradePositionToday * (double)p.Stock.Close - Math.Abs(TradePositionToday) * (double)p.Stock.Close * SA,
                    NAV = (double)p.Stock.Close * p.Position - Math.Abs(p.Position) * (double)p.Stock.Close * SA - Commission
                };
            }
               ).ToList()
            ).ToList();

但是,PerformanceSingleList中的所有Commision都为零,即使TradePositionToday不为零。此外,当我使用我的小样本数据时,没有这样的问题,只有当我使用真正的大数据时才会发生。

 [61]   { Stock = {{ Symbol = 1088 HK, Close = 12.860000000, Date = 3/7/2016 12:00:00 AM, Vol = 0.0490939300240106 }}, Position = -562, RealDesignPosition = 67, RealDesignTradeShare = 629, TradePositionToday = -562, Commission = 0, PLN = -7227.32, NAV = -7227.32 }    <Anonymous Type>
    Commission  0   double
    NAV -7227.32    double
    PLN -7227.32    double
    Position    -562    int
    RealDesignPosition  67  int
    RealDesignTradeShare    629 int
    Stock   { Symbol = "1088 HK", Close = 12.860000000, Date = {3/7/2016 12:00:00 AM}, Vol = 0.049093930024010565 } <Anonymous Type>
    TradePositionToday  -562    int

1 个答案:

答案 0 :(得分:4)

不幸的是,const double C = 10/10000确实是0。 10和10000都是整数,当除法完成后,结果存储为int(普通类型),然后转换为C为double。

如果你想让C不为零,你需要通过简单地使用这个语句明确地告诉其中一个值为float / double类型:

const double C = 10.0/10000;

const double C = ((double)10)/10000;