如何从 foreach 循环中将双精度值附加到 2D 数组,并访问上一个索引?

问题描述

我有一个名为 stockGains 的空二维数组,我试图将其附加 gains 的值(nextPrice/currentPrice 的值),但我似乎找不到合适的运算符或方法在 C# 中能够附加到我的二维数组并完成我的循环?目前,我错误地使用了 .Add 来举例。二维数组 stockGains 应动态调整大小。

double[,] stockGains = {};
   
foreach (double currentPrice in pricesMonth1AsList){

    // divide the nextPrice by currentPrice
    double gains = ((currentPrice+1)/currentPrice);

    // append the result to stockGains
    stockGains.Add(gains);

    // do this on repeat for every day of the month until the end of pricesMonth1Aslist
} 

我已将历史价格数据存储为一个名为 List<double>pricesMonth1AsList 进行迭代,其中每个 currentPrice 从第 1 天到第 30 天按顺序存储为双精度(您可以考虑索引列表的位置为 (day of the month - 1)nextPrice 是后一天的价格值(我在索引位置表示为 currentPrice+1)示例数据示例如下:>

20.35,30.5,40.2,50 代表第 1 天 [0]、第 2 天 [1]、第 3 天 [2]、第 4 天 [3] 等

例如,要计算的第一个增益将是 30.5/20.35,然后该值将存储为二维数组索引 0 中的第一个值,第二个值将是 40.2/20.35,第三个将 50/20.35 也存储在 stockGains 的索引 0 中,直到该月的最后一天。然后再次重复该过程,但从第 2 天开始,即40.2/30.5,50/30.5 等收益将存储在 stockGains 的索引 1 中。

最终目标是在最后的二维数组中找到单个最大增益值。

解决方法

我不确定这是否能回答您的问题;并且我调整了您的循环以能够访问前一个元素,这就是我使用 for 的原因。

我相信使用 Tuple<Tx,Ty> 会更容易(这是我的偏好)

从中创建一个 List<>,您将拥有一个 Add

var pricesMonth1AsList = new List<double>()
{
    0,1,2,3,4,5
};

//init
var list2D = new List<Tuple<double,double>>();
for (int i = 1; i < pricesMonth1AsList.Count; i++) {
    //calculate your values

    //since I did not understand the calculation,//here's just a dummy one
    var currentValue = pricesMonth1AsList[i];
    var previousValue = pricesMonth1AsList[i-1];
    
    double a = previousValue/currentValue;
    double b = i;

    //and add it as such
    list2D.Add(new Tuple<double,double>(a,b));
}

foreach(var item in list2D)
{
    Console.WriteLine($"{item.Item1} - {item.Item2}");  
}

输出:

0 - 1
0.5 - 2
0.6666666666666666 - 3
0.75 - 4
0.8 - 5