c++:定义分数类,可以对分数类对象的各种操作进行重载运算。1
发布网友
发布时间:2023-10-13 01:29
我来回答
共2个回答
热心网友
时间:2024-12-03 02:01
#include "stdafx.h"
#include <iostream>
#include <exception>
using namespace std;
class CFraction {
public:
CFraction(const int Numerator,const int Denominator):m_Numerator(Numerator),m_Denominator(Denominator)
{
if (0 == Denominator)
{
throw exception("Denominator should not be zero");
}
int tmp = abs(*(m_Numerator,m_Denominator));
if (0<m_Numerator*m_Denominator)
{
m_Numerator = abs(m_Numerator/tmp);
}else
{
m_Numerator = -abs(m_Numerator/tmp);
}
m_Denominator /= tmp;
m_Denominator = abs(m_Denominator);
}
static int *(int m, int n){
if(m%n==0)
return n;
return *(n, m%n);
}
friend ostream& operator<<(ostream& out,const CFraction& object);
friend CFraction operator+(const CFraction& F1,const CFraction&F2);
friend CFraction operator-(const CFraction& F1,const CFraction&F2);
friend CFraction operator*(const CFraction& F1,const CFraction&F2);
friend CFraction operator/(const CFraction& F1,const CFraction&F2);
private:
int m_Numerator;
int m_Denominator;
};
ostream& operator<<(ostream& out,const CFraction& object) {
if (0 == object.m_Numerator)
{
return out<<"0";
}
if (object.m_Denominator == object.m_Numerator)
{
return out<<"1";
}
out<<object.m_Numerator<<"/"<<object.m_Denominator;
return out;
}
CFraction operator+(const CFraction& F1,const CFraction&F2)
{
int Numerator,Denominator;
Numerator = F1.m_Numerator * F2.m_Denominator + F2.m_Numerator*F1.m_Denominator;
Denominator = F1.m_Denominator*F2.m_Denominator;
return CFraction(Numerator,Denominator);
}
CFraction operator-(const CFraction& F1,const CFraction&F2)
{
int Numerator,Denominator;
Numerator = F1.m_Numerator * F2.m_Denominator - F2.m_Numerator*F1.m_Denominator;
Denominator = F1.m_Denominator*F2.m_Denominator;
return CFraction(Numerator,Denominator);
}
CFraction operator*(const CFraction& F1,const CFraction&F2)
{
int Numerator,Denominator;
Numerator = F1.m_Numerator * F2.m_Denominator - F2.m_Numerator*F1.m_Denominator;
Denominator = F1.m_Denominator*F2.m_Denominator;
return CFraction(F1.m_Numerator * F2.m_Numerator,F1.m_Denominator * F2.m_Denominator);
}
CFraction operator/(const CFraction& F1,const CFraction&F2)
{
if (0 == F2.m_Numerator)
{
throw exception("Denominator should not be zero");
}
int Numerator=F2.m_Denominator,Denominator=F2.m_Numerator;
return F1*CFraction(Numerator,Denominator);
}
int _tmain(int argc, _TCHAR* argv[])
{
CFraction aaa(1,2);
CFraction bbb(2,32);
CFraction ccc(54,-6);
CFraction ddd(-1,-5);
cout<<aaa<<endl;
cout<<bbb<<endl;
cout<<aaa+bbb<<endl;
cout<<aaa-bbb<<endl;
cout<<aaa*bbb<<endl;
cout<<aaa/bbb<<endl;
return 0;
}
闲的无聊。帮帮你吧
热心网友
时间:2024-12-03 02:01
#include<iostream>
#include<vector>
int main()
{
static std::vector<int> vec;
vec.push_back(vec.size());
std::cout<<vec[vec.size()-1]<<std::endl;
if (vec.size()<10)main();
return 0;