C++中的混合分数可以增强有理库

Mixed fractional numbers in C++ boost rational library

本文关键字:增强 混合 C++      更新时间:2023-10-16

是否可以在C++提升有理数库中初始化和使用混合小数?

如果你的意思是像这里: http://www.calculatorsoup.com/calculators/math/mixed-number-to-improper-fraction.php 那么肯定:

住在科里鲁

#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};
}

并像这样使用它:住在科里鲁

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

哪些打印

32/9 would be 3 5/9

奖金

还为机械手实现了快速和脏流提取:

住在科里鲁

#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 errorn";
}

指纹

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