1

可以将 boost multiprecision int 乘以浮点数吗?这不支持吗?

using bigint = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<>>;

boost::multiprecision::bigint x(12345678); 
auto result = x * 0.26   // << THIS LINE DOES NOT COMPILE
4

1 回答 1

1

不,不支持,因为它是有损的。

您可以显式进行转换:

Live On Coliru

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>

//using bigint = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<>>;
using bigint   = boost::multiprecision::cpp_int;
using bigfloat = boost::multiprecision::cpp_dec_float_50;

int main() {
    bigint x(12345678); 
    bigfloat y("0.26");
    std::cout << "x: " << x << "\n";
    std::cout << "y: " << y << "\n";
    bigfloat result = x.convert_to<bigfloat>() * y;

    //bigint z = result; // lossy conversion will not compile
    bigint z1 = static_cast<bigint>(result);
    bigint z2 = result.convert_to<bigint>();

    std::cout << "Result: " << result << "\n";
    std::cout << "z1: " << z1 << "\n";
    std::cout << "z2: " << z2 << "\n";
}

印刷

x: 12345678
y: 0.26
Result: 3.20988e+06
z1: 3209876
z2: 3209876

警告

一个常见的陷阱是惰性求值的表达式模板。使用临时对象时,它们是一个陷阱:

auto result = x.convert_to<bigfloat>() * bigfloat("0.26");

result此后使用的是Undefined Behavior,因为临时对象已被销毁。分配到bigfloat强制评估。

于 2018-01-22T16:04:06.307 回答