c++ - 使用 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;
}
解决方案
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 类型,它不是作为原始类型提供的。
我推荐使用类似boost
的multiprecision
库,boost中的库有多个后端,这个例子使用cpp_int
,它是一个只有头文件的库(你只需要包含头文件,不需要链接!)
如果您没有任何使用经验boost
,则需要先安装它:
#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;
}
在线演示。
推荐阅读
- c++ - 通过让用户输入数字来过滤链表
- python - 如何修复 TensorFlow InvalidArgumentError
- c++ - 当另一个线程正在写入该 Unordered_Map 时,我可以从 Unordered_map 读取吗?如果没有什么可能是并发症
- mysql - 如何在续集 findAll 中检索静态值作为列
- arangodb - 用于打印值数组的 Arango DB 过滤器查询
- python - 如何关闭动态创建的芹菜实例的redis池连接
- tensorflow - kernel_initializer=None 是指 glorot_uniform_initializer 还是 he_uniform?
- mysql - MySQL递归查询cte
- javascript - Dialogflow V2 API 调用 Javascript
- regex - 从每个 id 的字符串中提取多个值