1

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

  • Because you added `using namespace std;` I dont know if its picking up the C++ or the C function, but in C the abs function takes and returns int, for long long its llabs. Yet another reason why `using namespace std;` is bad. – Borgleader Aug 12 '17 at 15:01
  • This works perfectly OK for me ([demo](http://ideone.com/19dOYm)). Voting to close as non-reproducible. – Sergey Kalinichenko Aug 12 '17 at 15:01
  • 2
    @dasblinkenlight I'd consider this a valid question. Whether the code above works as intendet is compiler-dependent. – chtz Aug 12 '17 at 17:13

2 Answers2

3

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";
}
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

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
  • 2
    There is nothing wrong with adding the values while "absing" them. – Baum mit Augen Aug 12 '17 at 15:04
  • @BaummitAugen I don't know if you're targeting me or something but I don't like you. Saying this in a respective manner. Here is my result when I add them while they're "absing". 1000000000000000000 2 1000000000000000000 When I do it my way it works. Can you explain that too? Instead of saying nothing wrong? – Tuğberk Kaan Duman Aug 12 '17 at 15:06
  • well the , work well for me without change the code – Kurniadi Ahmad Wijaya Aug 12 '17 at 15:07
  • @TuğberkKaanDuman Don't worry, I'm not targeting anyone, I just watch the tag C++. Regarding your question, feel free to post that as an actual question with a MCVE and I'm sure someone will handle it. – Baum mit Augen Aug 12 '17 at 15:08
  • @BaummitAugen okay then, I'm posting a new question. I hope you can get me an answer for it, because I don't know. – Tuğberk Kaan Duman Aug 12 '17 at 15:09