gpt4 book ai didi

c++ - boost 多精度 cpp_int 乘以 float

转载 作者:行者123 更新时间:2023-11-30 05:05:25 24 4
gpt4 key购买 nike

可以将 boost 多精度整数乘以 float 吗?不支持吗?

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

最佳答案

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

您可以明确地进行转换:

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");

此后使用 resultUndefined Behaviour ,因为临时文件已被销毁。分配给 bigfloat 会强制进行评估。

关于c++ - boost 多精度 cpp_int 乘以 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48383986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com