Rich C Rich C - 3 months ago 7
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

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

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
1
.

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);
minutesCounted++;
Console.WriteLine(minutesCounted + totalSeconds);
}

Console.WriteLine(security + totalSeconds);
Console.WriteLine(minutesCounted);
File.Delete(unzippedFolder[0]);

if (totalSeconds > 1)
{
Console.WriteLine(true);
}
else
{
Console.WriteLine(false); // This is returning false
}
Console.ReadLine();

Answer

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)