Array.Sum()导致溢出

时间:2018-10-31 02:42:48

标签: c# arrays sum int overflow

我有一个这样的int数组

int[] arr = {256741038,623958417,467905213,714532089,938071625};

然后我创建了一个int64变量

Int64 sum = arr.Sum();

但是这导致了溢出

  

运行时异常(第19行):算术运算导致   溢出。

如何不使用循环将其总结而解决此问题? (数组类型必须为int)

5 个答案:

答案 0 :(得分:7)

您需要将值强制转换为long(或其他需要使用大数字的数据类型,但由于您使用的是Int64 ...):

long sum = arr.Sum(v => (long)v);

答案 1 :(得分:3)

您必须将其强制转换很长时间,以免溢出

var result = arr.Select(x => (long)x).Sum();

int (C# Reference)

  

范围= -2,147,483,6482,147,483,647

某些背景,这是Sum的源代码

public static int Sum(this IEnumerable<int> source) 
{
      if (source == null) throw Error.ArgumentNull("source");
      int sum = 0;
      checked 
      {
          foreach (int v in source) 
             sum += v;
      }
      return sum;
}

意思是,不管您是否喜欢,有人正在使用for循环,另外使用checked就是抛出它的原因:)

checked (C# Reference)

  

checked关键字用于显式启用以下内容的溢出检查:   整型算术运算和转换。

答案 2 :(得分:0)

在整数数组上调用sum时,输出类型为整数,并且输入数字的总和大于整数最大值。就像@TheGeneral所说的sum方法检查溢出并抛出异常。

您可能希望sum方法的返回结果很长,但是其返回类型是整数。

int a = 256741038;
int b = 623958417;
int c = 467905213;
int d = 714532089;
int e = 938071625;

long sumInt = a + b + c + d + e;
//-1293758914 //overflow happened withoud exception
long sumLong = (long)a + b + c + d + e;//clr now the result may be more than int.maxvalue
//3001208382

答案 3 :(得分:0)

您可以找到如下所示的总和

.transform(Transformers.toJson())

Datatype and Range Reference

答案 4 :(得分:0)

一个较短的方法如下所示

using System;
namespace Test
{
    public partial class TestPage : System.Web.UI.Page
    {
        public int[] p = { 999999999, 999999999, 999999999, 999999999, 999999999 };
        protected void Page_Load(object sender, EventArgs e)
        {
            long s = Sum;
        }
        public long Sum
        {
            get { long s = 0; Array.ForEach(p, delegate (int i) { s += i; }); return s; }
        }        
    }
}

希望这会对您有所帮助。

相关问题