通过for循环加总 - 总计为0

时间:2016-04-29 12:51:09

标签: c# loops for-loop

我有一种方法可以从包含训练数据的文件中计算出区间。它检测到尖峰和功率下降以计算出间隔,我正在开发一种方法来计算每个间隔的平均值。这是方法:

public void getIntervalData()
        {
            //Remove first drop anomaly
            drops.Remove(0);        
            int intervalAltitude;
            int intervalPower;
            int intervalSpeed;
            int altitudeAddUp = 0;
            int powerAddUp = 0;
            int speedAddUp = 0;   
            int counter = 0;
            //Loop through to get all spikes and drops
            for (int j = 0; j < spikes.Count(); j++)
            {                
                int firstNumber = Convert.ToInt32(spikes[j]);
                int secondNumber = Convert.ToInt32(drops[j]);
                MessageBox.Show(firstNumber.ToString());
                counter++;
                //Difference to work out averages
                int difference = secondNumber - firstNumber;       
                //Get seperate interval data (first number = spike, second number = drop)
                for (int i = firstNumber; i < secondNumber; i++)
                {                      
                    int altitudeNumber = altitudeList[i];
                    int powerNumber = powerList[i];
                    int speedNumber = Convert.ToInt32(speedList[i]);                   
                    //Add up data
                    altitudeAddUp += altitudeNumber;     
                    powerAddUp += powerNumber;
                    speedAddUp += speedNumber;                    
                }
                MessageBox.Show("Alt add up:" + altitudeAddUp.ToString());
                intervalAltitude = altitudeAddUp / difference;
                intervalPower = powerAddUp / difference;
                intervalSpeed = speedAddUp / difference;  
                intervalAverages.Add(new Tuple<int, int, int>(intervalAltitude, intervalPower, intervalSpeed));
                MessageBox.Show("Interval: " + counter.ToString() + ": Avgs: " + intervalAverages[0]);
            }
            MessageBox.Show("Interval averages added. There were: " + counter + " intervals"); 
        }

altitudeAddUp,powerAddUp和speedAddUp始终为0,但我无法弄清楚为什么它没有加起来。可能是一个菜鸟错误我只是看不到它。

我之前使用过一个消息框来测试altitudeNumber,powerNumber和speedNumber是否包含数据,但是它们不会相加。

1 个答案:

答案 0 :(得分:1)

我认为问题是所有变量都是整数。并且整数没有任何小数精度,这意味着如果区间为0.999,则实际整数值为0(0.999不作为整数存在,值为在致电ToInt32时截断。

使用floatdoubledecimal,具体取决于精确度和范围的需要。