Rich C Rich C - 1 year ago 64
C# Question

Positive addition operations producing a negative number

I am writing a script to take a series of number from a csv file and total them.

I have extracted the values from the csv into a

and am looping over that to add them together.
The numbers are millisecond representations of each minute in the day, so generally starting at
and incrementing by

For some reason though, the final numbers appear to be negative.
I am checking at the end of the addition operations and the final count is less than

I tried printing the numbers to the console and they are correct, I guess something wrong somewhere else?

Screenshot of sample out

enter image description here

Thanks in advance.

var totalSeconds = 0;
var minutesCounted = 0;
var unzippedFolder = Compression.UnzipToFolder(zipPath);
var listOfSeconds = ReadCsvIndex(unzippedFolder[0], ",", 0, true);

foreach (var second in listOfSeconds)
// Console.WriteLine(Int32.Parse(second)); // Prints correct numbers
totalSeconds += Int32.Parse(second);
Console.WriteLine(minutesCounted + totalSeconds);

Console.WriteLine(security + totalSeconds);

if (totalSeconds > 1)
Console.WriteLine(false); // This is returning false

Answer Source

Use a long value instead of the default int for that totalSeconds. The value apparently goes above Int32.MaxValue, so the value wraps around to negative that.

A long has a much higher max value, so you will not get this overflow effect (at least, not as soon)