是否可以在C ++ boost rational library中初始化和使用混合分数?
答案 0 :(得分:2)
如果您的意思是: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
同时实施快速&amp;操纵器的脏流提取:
<强> 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