gpt4 book ai didi

c++ - C++ boost rational 库中的带分数

转载 作者:行者123 更新时间:2023-11-30 03:31:35 26 4
gpt4 key购买 nike

是否可以在 C++ boost rational 库中初始化和使用带分数?

最佳答案

如果您的意思是:http://www.calculatorsoup.com/calculators/math/mixed-number-to-improper-fraction.php然后确定:

Live On Coliru

#include <boost/rational.hpp>
#include <iostream>

using R = boost::rational<int>;

int main() {
std::cout << "3 + 5/9: " << 3 + R(5,9) << "\n";
}

打印

3 + 5/9: 32/9

如果您的意思是输出格式,您可以制作自己的小型 IO 操纵器:

template <typename R>
struct as_mixed_wrapper {
R value;
friend std::ostream& operator<<(std::ostream& os, as_mixed_wrapper const& w) {
auto i = boost::rational_cast<typename R::int_type>(w.value);
return os << i << " " << (w.value - i);
}
};

template <typename R> as_mixed_wrapper<R> as_mixed(R const& value) {
return {value};
}

然后像这样使用它: Live On Coliru

auto n = 3 + R(5,9);
std::cout << n << " would be " << as_mixed(n) << "\n";

哪个打印

32/9 would be 3 5/9

奖金

还为操纵器实现了一个快速且肮脏的流提取:

Live On Coliru

#include <boost/rational.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>

using R = boost::rational<int>;

template <typename R>
struct as_mixed_wrapper {
R* value;
friend std::ostream& operator<<(std::ostream& os, as_mixed_wrapper const& w) {
auto i = boost::rational_cast<typename R::int_type>(*w.value);
return os << i << " " << (*w.value - i);
}

friend std::istream& operator>>(std::istream& is, as_mixed_wrapper const& w) {
typename R::int_type i, d, n;
char c;
if ((is >> i >> d >> c) && (c == '/') && (is >> n))
*w.value = i + R(d,n);
return is;
}
};

template <typename R> as_mixed_wrapper<R> as_mixed(R& value) {
return {&value};
}

int main() {
auto n = 3 + R(5,9);
std::cout << n << " would be " << as_mixed(n) << "\n";

std::istringstream iss("123 7 / 13");
if (iss >> as_mixed(n))
std::cout << n << " would be " << as_mixed(n) << "\n";
else
std::cout << "Parse error\n";
}

打印

32/9 would be 3 5/9
1606/13 would be 123 7/13

关于c++ - C++ boost rational 库中的带分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44110622/

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