std::ratio_add
来自cppreference.com
在标头 <ratio> 定义 | ||
template<class R1, class R2 > using ratio_add =/* 见下文 */; | (C++11 起) | |
别名模版 std::ratio_add
指代 std::ratio 的特化 R1
和 R2
所表示的二个准确有理分数的相加结果。
结果是 std::ratio 的特化 std::ratio<U, V>,满足给定 Num == R1::num* R2::den+ R2::num* R1::den 与 Denom == R1::den* R2::den(计算无算术溢出),U
为 std::ratio<Num, Denom>::num 而 V
为 std::ratio<Num, Denom>::den。
[编辑]注解
若 U
或 V
不能以 std::intmax_t
表示,则程序非良构。若 Num
或 Denom
不能以 std::intmax_t
表示,除非实现生成 U
与 V
的正确值,否则程序非良构。
上述定义要求 std::ratio_add<R1, R2> 的结果已被约分到最简分数;例如,std::ratio_add<std::ratio<1, 3>, std::ratio<1, 6>> 与 std::ratio<1, 2> 是同一类型。
[编辑]示例
运行此代码
#include <iostream>#include <ratio> int main(){using two_third =std::ratio<2, 3>;using one_sixth =std::ratio<1, 6>;using sum = std::ratio_add<two_third, one_sixth>; std::cout<<"2/3 + 1/6 = "<< sum::num<<'/'<< sum::den<<'\n';}
输出:
2/3 + 1/6 = 5/6
[编辑]参阅
(C++11) | 在编译时相减两个 ratio 对象 (别名模板) |