如何在C++中将big int转换为double

问题描述 投票:0回答:1

在C++中,我想得到一个大整数的平方根。该数字小于双精度数表示的最大整数,因此这种方法应该可行。 ttmath 库没有平方根函数。

我正在使用 ttmath 库来处理大整数。

我写了以下程序:

#include <ttmath/ttmath.h>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    ttmath::UInt<4>  a = "234567890123456789012345";

    // convert BigInt to double
    double d=(double)a;

    // then take the square root of the double
    double b = sqrt(d);

    cout << b << endl;
}

编译它会导致以下错误:

cannot convert 'ttmath::UInt<3>' to 'double' without a conversion operator
    double d=(double)a;

所以它不喜欢使用强制转换来转换为双精度。

所需的转换运算符是什么?

c++ type-conversion biginteger ttmath
1个回答
0
投票

ttmath 库不允许直接将

Int
UInt
转换为
double
。 你需要经历
ttmath::Big

ttmath::UInt<4>  a = "234567890123456789012345";

// 12 (signed) exponent bits, 52 mantissa bits;
// that's all we need for converting to double precision, assuming binary64 representation
ttmath::Big<12, 52> = a;
double d = a.ToDouble();

话虽如此,您不需要转换为

double
来计算平方根或打印。

ttmath::Big<12, 52> = a;
a.Sqrt();
std::cout << a;
© www.soinside.com 2019 - 2024. All rights reserved.