📜  C++中的比率操作|一组1(算术)

📅  最后修改于: 2021-05-25 20:21:11             🧑  作者: Mango

下面在本文中讨论一种增加比率的方法

程序将两个分数相加

上述方法涉及繁琐而冗长的任务。但是C++有一个头文件,这使我们可以使用各种内置的Templete别名来操纵比率。从C++ 11开始引入此头文件。

1. ratio_add :-此模板别名用于添加两个比率,以最简单的形式返回结果。它返回两个成员常量numden,分别表示分子和分母。

2. ratio_subtract :-此模板别名用于减去两个比率,以最简单的形式返回结果。它返回两个成员常量numden,分别表示分子和分母。它从ratio1中减去ratio2

// C++ code 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. ratio_multiply :此模板别名用于将两个比率相乘,以最简单的形式返回结果。它返回两个成员常量numden,分别表示分子和分母。

4. ratio_divide :-这个模板别名用于划分两个比率,以最简单的形式返回结果。它返回两个成员常量numden,分别表示分子和分母。它用ratio1除以ratio2

// C++ code 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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”