Kurniadi Ahmad Wijaya
Kurniadi Ahmad Wijaya

Reputation: 21

How to use addition in long long int?

i have write a code for addition with the variable long long but the summary is not like the normal addition

here is the code :

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
long long int a, b, c;
cout << "" << "";
cin >> a >> b;
c = abs(a) + abs(b);
cout << c;
cout << "\n";
}

when i input number like 1000000000000000000 2

the outpout is 1486618626 not 1000000000000000002

Upvotes: 1

Views: 3711

Answers (2)

Baum mit Augen
Baum mit Augen

Reputation: 50081

The old C function ::abs from <stdlib.h> takes and returns int, which cannot hold values that big on your platform.

Use std::abs from <cmath> (C++17 and later) or <cstdlib> instead.

Also, get rid of that using namespace std; and properly qualify the names instead. See Why is "using namespace std" considered bad practice?

Complete code:

#include <iostream>
#include <cstdlib>

int main() {
    long long int a, b;
    std::cin >> a >> b;
    long long int c = std::abs(a) + std::abs(b);
    std::cout << c;
    std::cout << "\n";
}

Upvotes: 3

Tuğberk Kaan Duman
Tuğberk Kaan Duman

Reputation: 950

Try using <cmath> instead of <stdlib.h>.

Also, don't add values while abs()ing them. Do it this way.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    long long int a, b;
    long long int c;

    cin >> a >> b;

    a = abs(a);
    b = abs(b);

    c = a + b;
    cout << c;
    cout << endl;
}

Code works just fine.

Input and output:

1000000000000000000 2
1000000000000000002

Upvotes: 0

Related Questions