std::ratio初探
1. std::ratio简介2. std::ratio参数
2.1 模板参数2.2 成员常量2.3 成员类型 3. std::ratio实例化4. ratio运算5. 简单程序举例
1. std::ratio简介std::ratio是C++11标准之后推出的库模板,头文件包含写法为#include
声明写作:
templateclass ratio;
这个模板常用作有理数定义,由一个分子 n u m e r a t o r numerator numerator和分母 d e n o m i n a t o r denominator denominator来定义.
2. std::ratio参数 2.1 模板参数N
分子.
它的绝对值可以是intmax_t范围内的所有整型数.
D
分母.
它的绝对值可以是intmax_t范围内除0以外的所有整型数.
2.2 成员常量num
分子
den
分母
num和den的值表示N:D的最简约分,这表示,num和den的值可能和原始的N:D定义不同:
如果N和D的最大公因数不是1,那么num和den就分别等于N和D除以它们的最大公因数;符号通常由num决定(den恒为正):如果D是负的,那么num和N的符号相反. 2.3 成员类型
type
定义为ratio
预定义的比例值如下表所示
| type | definition | description |
|---|---|---|
| yocto | ratio<1, 1000000000000000000000000> | 1 0 − 24 10^{-24} 10−24* |
| zepto | ratio<1, 1000000000000000000000> | 1 0 − 21 10^{-21} 10−21* |
| atto | ratio<1, 1000000000000000000> | 1 0 − 18 10^{-18} 10−18 |
| femto | ratio<1, 1000000000000000> | 1 0 − 15 10^{-15} 10−15 |
| pico | ratio<1, 1000000000000> | 1 0 − 12 10^{-12} 10−12 |
| nano | ratio<1, 1000000000> | 1 0 − 9 10^{-9} 10−9 |
| micro | ratio<1, 1000000> | 1 0 − 6 10^{-6} 10−6 |
| milli | ratio<1, 1000> | 1 0 − 3 10^{-3} 10−3 |
| centi | ratio<1, 100> | 1 0 − 2 10^{-2} 10−2 |
| deci | ratio<1, 10> | 1 0 − 1 10^{-1} 10−1 |
| deca | ratio<10, 1> | 1 0 1 10^1 101 |
| hecto | ratio<100, 1> | 1 0 2 10^2 102 |
| kilo | ratio<1000, 1> | 1 0 3 10^3 103 |
| mega | ratio<1000000, 1> | 1 0 6 10^6 106 |
| giga | ratio<1000000000, 1> | 1 0 9 10^9 109 |
| tera | ratio<1000000000000, 1> | 1 0 12 10^{12} 1012 |
| peta | ratio<1000000000000000, 1> | 1 0 15 10^{15} 1015 |
| exa | ratio<1000000000000000000, 1> | 1 0 18 10^{18} 1018 |
| zetta | ratio<1000000000000000000000, 1> | 1 0 21 10^{21} 1021* |
| yotta | ratio<1000000000000000000000000, 1> | 1 0 24 10^{24} 1024* |
这些名称都和国际单位制表示一致.
标星号的变量单位必须在分子分母类型定义为intmax_t下才能使用.
4. ratio运算ratio也提供了一些简单运算,如下表所示:
| 名称 | 涵义 |
|---|---|
| ratio_add | 求和 |
| ratio_subtract | 相减 |
| ratio_multiply | 相乘 |
| ratio_divide | 相除 |
| ratio_equal | 关系运算,相等 |
| ratio_greater | 关系运算,大于 |
| ratio_greater_equal | 关系运算,大于等于 |
| ratio_less | 关系运算,小于 |
| ratio_less_equal | 关系运算,小于等于 |
| ratio_not_equal | 关系运算,不等于 |
// ratio example #include#include int main (int argc, char* argv[]) { typedef std::ratio<1,3> one_third; typedef std::ratio<2,4> two_fourths; std::cout << "one_third= " << one_third::num << "/" << one_third::den << std::endl; std::cout << "two_fourths= " << two_fourths::num << "/" << two_fourths::den << std::endl; typedef std::ratio_add sum; std::cout << "sum= " << sum::num << "/" << sum::den; std::cout << " (which is: " << ( double(sum::num) / sum::den ) << ")" << std::endl; std::cout << "1 kilogram has " << ( std::kilo::num / std::kilo::den ) << " grams"; std::cout << std::endl; system("pause"); return 0; }
one_third= 1/3 two_fourths= 1/2 sum= 5/6 (which is: 0.833333) 1 kilogram has 1000 grams 请按任意键继续. . .
以上内容基本来自
https://www.cplusplus.com/reference/ratio/ratio/



