c# - 数组中的正整数总和为负数

标签 c# arrays negative-number sum-of-digits

我有这段代码:

int[] primes = generatePrimes(bound);

int sum = 0;
for (int i = 0; i < primes.GetLength(0); i++)
{
    if (sum < 0)
    {
        Console.WriteLine(sum);
    }
    sum += primes[i];
}

我已经检查以确保我的数组“primes”只包含像这样的正整数:

if (primes[i] < 0)
{
    Console.WriteLine(primes[i]);
}

但不会打印任何内容。但是,出于某种原因,总和有时会是负数,并且会在我运行第一段代码时打印出来。数组的长度是148933。我不太了解C#,但我不认为长度在这里很重要? :S

如果有人知道为什么会这样,我将不胜感激。

最佳答案

the length of the array is 148933.

很可能您的求和超出了 int (-2,147,483,648 到 2,147,483,647) 的可能值,这就是您看到负数的原因。

使用 long 进行求和计算。但你可能需要 BigInteger计算总和。

关于c# - 数组中的正整数总和为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24678514/

相关文章:

c# - 如何重新排序 DataGridView 中的列?

pattern-matching - OCaml:与任何否定匹配

java - 计算数组中的负数

assembly - 汇编中减去负数

javascript - 我如何遍历对象并按 Javascript 中的时间戳进行分类?

c# - 如何在 C# 中用字符串实例化对象并发送参数?

c# - 为什么编码后的 key 不等于原始 key ?

C# : Check if two objects have same data

arrays - R将data.frame转换为json

c - 分割字符串函数的段错误