这个列表有 5 个对象,如果我用第二个对象减去第一个对象:[0]-[1] 并将其放入一个新列表中,它就可以工作。但看看这个:[2]-[3], [4]-[5] =?请注意,我有 [4] 作为我的第 5 项,但我没有“第 6 项”:[5] 因为这个列表只有 5 项,我要减去什么?我会收到错误/异常吗?
var wqat = 1.1;
var rat = .2;
var eat = .8;
var baat = 1.2;
var baat2 = 1.8;
List<double> test = new List<double>();
List<double> theOneList = new List<double>();
theOneList.Add(wqat);
theOneList.Add(rat);
theOneList.Add(eat);
theOneList.Add(baat);
theOneList.Add(baat2);
theOneList = theOneList.OrderByDescending(z => z).ToList();
for (int i = 0; i < 5; i++)
{
test.Add(theOneList[i] - theOneList[i + 1]);
Console.WriteLine(test[i]);
}
我在尝试减法时遇到系统超出范围异常,我尝试实现的一个可能的解决方案是,如果列表是“奇数”,则只需将“0”添加到列表中,它就会使其成为偶数对象,这样我就可以一次平静地减去 2 个数字。
最佳答案
上述评论摘要:
var wqat = 1.1;
var rat = .2;
var eat = .8;
var baat = 1.2;
var baat2 = 1.8;
// Add's are hard to read
List<double> theOneList = new List<double>() {
wqat, rat, eat, baat, baat2
};
// Inplace sorting, "-" for the descending order
theOneList.Sort((x, y) => -x.CompareTo(y));
// Or (worse) Linq, do not forget to assign the result
// theOneList = theOneList.OrderByDescending(z => z).ToList();
List<double> test = new List<double>();
// No magic numbers (i.e. 4) - no pesky out of range exceptions
for (int i = 0; i < theOneList.Count - 1; ++i)
test.Add(theOneList[i] - theOneList[i + 1]);
// Output (mix output and algorthim is not a good idea)
Console.Write(String.Join(Environment.NewLine, test));
关于c# - 将数学公式应用到新列表时如何保持精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34770670/