Sum of elements but got a wrong result

Posted on 2011-04-28
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

Open in new window

Question by:zhshqzyc
    LVL 5

    Accepted Solution

    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

    LVL 7

    Expert Comment

    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.

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    755 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

    Need Help in Real-Time?

    Connect with top rated Experts

    23 Experts available now in Live!

    Get 1:1 Help Now