?
Solved

Sum of elements but got a wrong result

Posted on 2011-04-28
2
Medium Priority
?
253 Views
Last Modified: 2012-05-11
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

Open in new window

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

Open in new window

What I got
-1273333879

Open in new window

Thanks
0
Comment
Question by:zhshqzyc
2 Comments
 
LVL 5

Accepted Solution

by:
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;
}

Open in new window

0
 
LVL 7

Expert Comment

by:jdavistx
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Article by: Najam
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

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question