Adding numbers larger than long long in C++

前端 未结 4 1547
庸人自扰
庸人自扰 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: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 
    #include 
    
    #include 
    
    int main()
    {
       using namespace boost::multiprecision;
    
       cpp_int i; // multi-precision integer 
    
       i = std::numeric_limits::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.

提交回复
热议问题