C++ での比率操作 |セット 1 (算術)
C++ を使用すると、分数の加減乗除演算を実行できます。比率を追加する 1 つの方法については、次の記事で説明しています。 2 つの分数を加算するプログラム。 ここで使用されている方法は退屈で時間がかかるため、これを克服するために、より良い方法が C++ に導入されました。の
この記事では、 C++ での算術比操作。 次の関数が使用されます。
- 比率追加
- 比率減算
- 比率乗算
- 比率除算
1) 比率追加: このテンプレートのエイリアスは次の目的で使用されます。 2つの比率を加算する そしてそれを返します 最も単純な形で結果が得られます 。 2 つのメンバーの定数を返します で そして それ 分子と分母を表します。
2) 比率減算: このテンプレートのエイリアスは次の目的で使用されます。 2つの比率を引く そしてそれを返します 最も単純な形で結果が得られます 。 2 つのメンバーの定数を返します で そして それ 分子と分母を表します。それ 比率 1 から比率 2 を減算します 。
// C++ program to demonstrate the working of // ratio_add and ratio_subtract #include #include // for ratio manipulation using namespace std ; int main () { // Declaring ratios typedef ratio < 5 4 > ratio1 ; typedef ratio < 3 4 > ratio2 ; // Summing two ratios typedef ratio_add < ratio1 ratio2 > sum ; // Subtracting two ratios typedef ratio_subtract < ratio1 ratio2 > diff ; // printing sum of ratios cout < < 'The sum of ratios is : ' ; cout < < sum :: num < < '/' < < sum :: den ; cout < < endl ; // printing difference of ratios cout < < 'The difference of ratios is : ' ; cout < < diff :: num < < '/' < < diff :: den ; cout < < endl ; return 0 ; }
出力
The sum of ratios is : 2/1 The difference of ratios is : 1/2
3. 比率乗算: このテンプレートのエイリアスは次の目的で使用されます。 2 つの比率を掛ける そしてそれを返します 最も単純な形で結果が得られます 。 2 つのメンバーの定数を返します で そして それ 分子と分母を表します。
4.ratio_divide: このテンプレートのエイリアスは次の目的で使用されます。 2つの比率を割る そしてそれを返します 最も単純な形で結果が得られます 。 2 つのメンバーの定数を返します で そして それ 分子と分母を表します。それ 比率 1 を比率 2 で割ります 。
// C++ program to demonstrate the working of // ratio_multiply and ratio_divide #include #include // for ratio manipulation using namespace std ; int main () { // Declaring ratios typedef ratio < 5 4 > ratio1 ; typedef ratio < 3 4 > ratio2 ; // Multiplying two ratios typedef ratio_multiply < ratio1 ratio2 > prod ; // Dividing two ratios typedef ratio_divide < ratio1 ratio2 > div ; // printing product of ratios cout < < 'The product of ratios is : ' ; cout < < prod :: num < < '/' < < prod :: den ; cout < < endl ; // printing division of ratios cout < < 'The division of ratios is : ' ; cout < < div :: num < < '/' < < div :: den ; cout < < endl ; return 0 ; }
出力
The product of ratios is : 15/16 The division of ratios is : 5/3
次のセットについては、この記事を参照してください。
- C++ での比率操作 |セット 2 (比較)