C++/ratio

维基教科书,自由的教学读本
< C++

定义了类模板:

template<
    std::intmax_t Num,
    std::intmax_t Denom = 1
> class ratio;

类模板std::ratio提供了编译时有理数算术支持。类模板的实例表示有限的有理数,只要其分子和分母可表示为编译时的类型std::intmax_t的常量。此外,分子不可以为0,也不可以为最大负值。

两个静态数据类型num 和 den表示除掉最大公约数之后的分子和分母的值。但是,两个std::ratio有不同的Num和Denom是不同的类型,即使它们在约减后表示相同有理数。有理数类型的成员type表示其最约简的有理数形式,如std::ratio<3, 6>::type 为 std::ratio<1, 2>。

标准库已经定义了SI有理数:

  • yocto std::ratio<1, 1000000000000000000000000>, 如果std::intmax_t能表示分母
  • zepto std::ratio<1, 1000000000000000000000>, 如果std::intmax_t能表示分母
  • atto std::ratio<1, 1000000000000000000>
  • femto std::ratio<1, 1000000000000000>
  • pico std::ratio<1, 1000000000000>
  • nano std::ratio<1, 1000000000>
  • micro std::ratio<1, 1000000>
  • milli std::ratio<1, 1000>
  • centi std::ratio<1, 100>
  • deci std::ratio<1, 10>
  • deca std::ratio<10, 1>
  • hecto std::ratio<100, 1>
  • kilo std::ratio<1000, 1>
  • mega std::ratio<1000000, 1>
  • giga std::ratio<1000000000, 1>
  • tera std::ratio<1000000000000, 1>
  • peta std::ratio<1000000000000000, 1>
  • exa std::ratio<1000000000000000000, 1>
  • zetta std::ratio<1000000000000000000000, 1>, 如果std::intmax_t能表示分子
  • yotta std::ratio<1000000000000000000000000, 1>, 如果std::intmax_t能表示分子