简体   繁体   English

数组中的正整数总和为负数

[英]Positive integers in array sum to a negative number

I have this piece of code: 我有这段代码:

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];
}

I have checked to make sure that my array "primes" only contains positive integers like so: 我检查以确保我的数组“素数”仅包含正整数,如下所示:

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

But nothing will be printed. 但是不会打印任何内容。 However, for some reason the sum will sometimes be negative and will get printed when I run the first piece of code. 但是,由于某种原因,总和有时会是负数,并且在我运行第一段代码时会被打印出来。 The length of the array is 148933. I don't know that much C#, but I didn't think that the length should matter here? 数组的长度为148933。我不知道C#这么多,但是我认为长度在这里不重要吗? :S :S

If someone knows why this is happening, I would greatly appreciate any help. 如果有人知道为什么会这样,我将不胜感激。

the length of the array is 148933. 数组的长度为148933。

Most probably your sum is over flowing the possible values for int (-2,147,483,648 to 2,147,483,647) , that is why you see negative numbers. 最有可能您的总和超过了int的可能值(-2,147,483,648到2,147,483,647) ,这就是为什么看到负数的原因。

Use long for your sum calculation. 使用long进行总和计算。 But you might need BigInteger to calculate the sum. 但是您可能需要BigInteger来计算总和。

The sum of the first 21000 primes is 2 368 647 159 (according to Wolfram Alpha). 前21000个素数的总和是2368647159(根据Wolfram Alpha)。 This value will not fit in a 32 bit signed integer. 该值将不适合32位有符号整数。 It will be appear as a negative number. 它会显示为负数。

The sum of the first 148933 primes is 142 913 828 922. This can be represented as a 64 bit integer. 前148933个质数的总和为142913828922。这可以表示为64位整数。

Whatever sum you calculated in a 32 bit number will be wrong, and could be either positive or negative depending on magnitude. 无论您用32位数字计算出的总和都将是错误的,并且根据大小可能是正数或负数。

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

This does not ensure that there are only positive numbers in the array, it only lets you know when there is a negative prime number. 这不能确保数组中只有正数,它只会让您知道何时有负质数。

If you do not want to include negatives into the sum, try this: 如果您不想在总和中包含负数,请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM