在C ++中添加大于long long的数字 [英] Adding numbers larger than long long in C++

查看:156
本文介绍了在C ++中添加大于long long的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加两个数字,这是一个长整数可以容纳的最大值;并打印出来。如果我不将sum的值存储在变量中,则只使用 cout打印即可,那么我的计算机将能够打印出来吗?该代码将是这样的:

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 using "cout" then will my computer will be able to print that? The code will be some what like this:

cout<<theLastValueOfLongLong + theLastValueOfLongLong;

我假设long long int是最大的主变量类型。

I am assuming that a long long int is the largest primary variable type.

推荐答案

如果不想溢出,则需要使用长整数库,例如 Boost.Multiprecision。然后,您可以执行任意长整数/ fp操作,例如

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;
}

特别是,Boost.Multiprecision非常易于使用,并且可以自然地集成使用C ++流,使您几乎可以将类型视为内置类型。

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.

这篇关于在C ++中添加大于long long的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆