首页 > 解决方案 > 使用 64 位数据类型时出错

问题描述

我有一个代码,其功能类似于上述代码,当我运行此代码并输入字符串的值时265.145,它可以正常工作,但是当我输入的值大到5415485451447454554545415454.84845151151511515151515151.

它抛出一个错误说terminate called after throwing an instance of ‘std out of range’ what():stoull

#include<iostream

using namespace std;

int main() {

    string y;

    cin>>y;

    int64_t z;

    z=stoull(y); 

    double x=stod(y);

    double d= x-z;

    cout<<d;

}

标签: c++

解决方案


stoll的文档显示,当转换的值超出范围时,我们会得到一个异常:

Exceptions
            * std::invalid_argument if no conversion could be performed
            * std::out_of_range if the converted value would fall out of the range of the
              result type or if the underlying function (std::strtoul or std::strtoull) sets
              errno to ERANGE.

int64_t一种类型在 x86_64 平台上可以容纳的最大值是9223372036854775807( std::numeric_limits<int64_t>::max()),对于您的用例,输入文件大于最大值,您需要一个大的 int 类型,它不是作为原始类型提供的。

我推荐使用类似boostmultiprecision库,boost中的库有多个后端,这个例子使用cpp_int,它是一个只有头文件的库(你只需要包含头文件,不需要链接!)

如果您没有任何使用经验boost,则需要先安装它:

  • 对于像 disto 这样的 ubuntu,只需使用命令sudo apt install libboost-dev
  • 对于 Windows,只需遵循本指南,或使用包管理器,如:nugetvcpkg
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
#include <istream>

int main() {
  using namespace boost::multiprecision;
  std::string str = "5415485451447454554545415454.84845151151511515151515151";
  std::istringstream oss(str);
  cpp_int u;
  oss >> u;
  std::cout << u << std::endl;

  return 0;
}


在线演示


推荐阅读