Solved

# Sum of elements but got a wrong result

Posted on 2011-04-28
Medium Priority
253 Views
Hi, I have a dictionary likes below.
``````1	247196267
2	242740058
3	199387333
4	191250869
5	180668669
6	170862814
7	158821315
8	146272142
9	140227932
10	135373753
11	134451767
12	132289492
13	114127715
14	106360481
15	100338578
16	88820312
17	78654554
18	76116660
19	63801064
20	62434810
21	46943739
22	49580137
23	154912956
``````
I want to summize it but got a negetive value. Why?
``````int sum1=0;
foreach (KeyValuePair<string, string> pair in dict)
{
int temp = Int32.Parse (pair.Value);
Console.WriteLine("key {0}, value {1}", pair.Key, pair.Value);
sum1 += temp;
}
``````
What I got
``````-1273333879
``````
Thanks
0
Question by:zhshqzyc

LVL 5

Accepted Solution

morgulo earned 2000 total points
ID: 35486968
Sum is greater than MaxInt. Try this:
``````long sum1=0;
foreach (KeyValuePair<string, string> pair in dict)
{
long temp = long.Parse (pair.Value);
Console.WriteLine("key {0}, value {1}", pair.Key, pair.Value);
sum1 += temp;
}
``````
0

LVL 7

Expert Comment

ID: 35487048
Someone correct me, but the reason the number actually becomes negative is because the sign bit is getting flipped to 1, as a result of the addition, which in turn a power of 10 precision is lost in order to gain the sign?

So, you could use a uint as well.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
###### Suggested Courses
Course of the Month15 days, 18 hours left to enroll