-3

when i try to add two long numbers it gives me minus result :

#include<iostream>
using namespace std;
int main ()
{
 int a=1825228665;
 int b=1452556585;
 cout<<a+b;
 return 0;
}

This gives me:

-1017182046
user3516293
  • 27
  • 1
  • 7

2 Answers2

0

It's overflowing of the type. When you add two big number that the result can't be stored in chosen type it get overfloved. In most cases it will wraped the number, but it's not defined in the standard. So in some compilers the result is undefined.

For int and other numeric types when program can't store this big number in it we can see a overflow of it.

Lets say that int can store number from -10 to 10, when you do this:

int a = 10;
int b = a+1;

You will get -10 in b or some random value (it can be anything because the result is undefined)

Ardel
  • 315
  • 2
  • 9
0

That's because the results overflows. Since the first bit in numeric signed data types is used for the sign representation. The specific representation is called Two's complement (Wikipedia article here). Practically a 1 in this bit maps to a - while a 0 to +. The solution to this problem is using a larger data type like long. Larger it means that the memory used to store it is bigger so the range of values increases.

marcyb5st
  • 252
  • 1
  • 5