c# - 将数学公式应用到新列表时如何保持精度?

标签 c#

这个列表有 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/

相关文章:

c# - 如何在更新查询中将格式为 test@test1.com 的电子邮件地址传递给 Access DB

c# - 是否有机会使用 Linq (C#) 获得唯一记录?

c# - 如何判断子线程是否完成

c# - 正在改变枚举的基础类型打破 wcf 契约(Contract)的变化?

c# - View 在屏幕上时如何修改 XAML 元素的颜色?

c# - 在c#wpf中选择FolderBrowserDialog的默认路径

c# - 获取 AppointmentItem 的日历所有者电子邮件地址

C# 在使用 ThreadPool 时,我可以将多个数据传递到我的目标方法吗?

c# - 从 WP7 中的代码调用后退按钮

c# - 如何将数据库数据缓存到内存中以供 MVC 应用程序使用?