Adding numbers larger than long long in C++

前端 未结 4 1548
庸人自扰
庸人自扰 2020-12-20 10:26

I want to add two numbers which is the largest values that a long long integer can hold; and print it. If I don\'t store the value of sum in a variable, I just print it usin

相关标签:
4条回答
  • 2020-12-20 11:03

    Since long long is signed, the addition overflows. This is Undefined Behavior and anything may happen. It's unlikely to format your harddisk, especially in this simple case.

    Once Undefined Behavior happens, you can't even count on std::cout working after that.

    0 讨论(0)
  • 2020-12-20 11:15

    If you don't want to overflow, then you need to use a "long integer" library, such as Boost.Multiprecision. You can then perform arbitrary-long integer/f.p. operations, such as

    #include <iostream>
    #include <limits>
    
    #include <boost/multiprecision/cpp_int.hpp>
    
    int main()
    {
       using namespace boost::multiprecision;
    
       cpp_int i; // multi-precision integer 
    
       i = std::numeric_limits<long long>::max();
    
       std::cout << "Max long long: " << i << std::endl; 
       std::cout << "Sum: " << i + i << std::endl;
    }
    

    In particular, Boost.Multiprecision is extremely easy to use and integrates "naturally" with C++ streams, allowing you to treat the type almost like a built-in one.

    0 讨论(0)
  • 2020-12-20 11:24

    No, at first it counts (theLastValueOfLongLong + theLastValueOfLongLong) (which causes overflow or freezes at max value available) and then it sends result into cout.<<(long long) operator

    0 讨论(0)
  • 2020-12-20 11:25

    It's the same as:

    long long temp = theLastValueOfLongLong + theLastValueOfLongLong;
    cout << temp;
    

    temp will contain the result of the addition, which will be undefined because you get an overflow, and then it will cout that result what ever it's value is.

    0 讨论(0)
提交回复
热议问题