c++ - Adding large numbers in C -


To add a large number when I'm a bit confused about the behavior of C, this is probably a starting question, but any Appreciate the help.

  Unsigned long total = 0; Total = 1124073472 + 283534 9 503; Total + = 2533359615; Printf ("total:% u \ n", total);   

The above print is not all right. The first joint result is fine, but the third plus throws off the total. I am thinking this is due to overflow. My question is, what is possible solution? Is there a solution without using third party libraries?

Note: I have tried different data types for the total. Some of these are DWORD64, INT64, LONG64, etc.

Thanks in advance.

You are right, this is due to overflow it will be fixed by using 64-bit type - You will need to change your printf () format string 64-bit type, though. You may find a 64-bit type for total a unsigned long time , but in the most secure way stdint.h . Here is an example program - I have also used to get inttypes.h to PRIu64 .

  #include & lt; Stdio.h & gt; # Include & lt; Stdint.h & gt; # Include & lt; Inttypes.h & gt; Int main (int argc, char ** argv) {uint64_t total = 0; Total = 1124073472 + 283534 9 503; Total + = 2533359615; Printf ("Total:%" PRIu64 "\ n", total); Return 0; }    

Comments