请考虑以下MCVE:
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
boost::multiprecision::cpp_int x = 10;
x *= 10000000000000000000000000000000000000000000000000000000000000;
std::cout<<x<<std::endl;
return 0;
}
由于该int
明显溢出,它会产生错误的结果。假设我不想涉及字符串,我如何才能正确执行此操作?是否有像"数字移位运算符"或幂函数之类的东西可以便宜(或最便宜)地做到这一点?
为什么?因为我有一个我编写的固定精度库,并且缩放内部整数需要此类操作 100% 安全。
在此处查找示例。
您需要
一个函数来自动生成所需的数字。
boost::multiprecision::cpp_int pow(boost::multiprecision::cpp_int value, boost::multiprecision::cpp_int exponent) {
if(exponent <= 0)
return 1;
else if(exponent == 1)
return value;
else {
if(exponent % 2 == 0) {
return pow(value * value, exponent / 2);
} else {
return value * pow(value, exponent - 1);
}
}
}
int main()
{
boost::multiprecision::cpp_int x = 10;
x *= pow(10, 61);//I believe this is the correct number of 0's from manually counting
std::cout<<x<<std::endl;
return 0;
}
如果 boost.multiprecision 有一个烘焙的pow
函数(我找不到),请改用它。