(使用Rational类)编写一个程序,使用Rational类计算下面的求和级数
这个类里好多东西都是连在一起的,想起了几天前专业课老师说的那句话,类是很好用的但是拔出萝卜带出泥,想用他一个,得用他一家,,,,
哎,不说了,上代码:
以下代码在VS2019上获得通过!
主函数代码:
#include "pch.h"
#include <iostream>
#include <sstream>
#include"Rational.h"
using namespace std;
int main()
{
Rational sum;
for (int i = 1; i < 100; i++)
{
Rational r(i, i + 1);
sum += r;
}
cout << sum.toString() << " " << endl;
return 0;
}
类头文件代码:
#pragma once
#include <string>
using namespace std;
class Rational
{
public:
Rational();
Rational(int num, int der);
int getNumerator()const;
int getDenominator()const;
Rational add(const Rational& secondRational)const;
Rational subtract(const Rational& SecondRational) const;
int CompareTo(const Rational& secondRational)const;
bool operator<(const Rational& SecondRational)const;
string toString()const;
double doubleValue()const;
Rational& operator+=(const Rational& secondRational);
private:
int numerator;
int denominator;
static int gcd(int n, int d);
};
类函数代码:
#include "pch.h"
#include "Rational.h"
#include<cstdlib>
#include<sstream>
Rational::Rational()
{
numerator = 0;
denominator = 1;
}
Rational::Rational(int numerator, int denominator)
{
int factor = gcd(numerator, denominator);
this->numerator = ((denominator > 0) ? 1 : -1) * numerator / factor;
this->denominator = abs(denominator) / factor;
}
int Rational::getNumerator()const
{
return numerator;
}
int Rational::getDenominator() const
{
return denominator;
}
int Rational::gcd(int n, int d)
{
int n1 = abs(n);
int n2 = abs(d);
int gcd = 1;
for (int k = 1; k <= n1 && k <= n2; k++)
{
if (n1 % k == 0 && n2 % k == 0)
{
gcd = k;
}
}
return gcd;
}
Rational Rational::add(const Rational& secondRational)const
{
int n = numerator * secondRational.getDenominator() +
denominator * secondRational.getNumerator();
int d = denominator * secondRational.getDenominator();
return Rational(n, d);
}
Rational Rational::subtract(const Rational& SecondRational) const
{
int n = numerator * SecondRational.getDenominator()
- denominator * SecondRational.getNumerator();
int d = denominator * SecondRational.getDenominator();
return Rational(n, d);
}
int Rational::CompareTo(const Rational& secondRational)const
{
Rational temp = subtract(secondRational);
if (temp.getNumerator() < 0)
return -1;
else if (temp.getNumerator() == 0)
return 0;
else
return 1;
}
bool Rational::operator<(const Rational& SecondRational)const
{
if (CompareTo(SecondRational) < 0)
{
return true;
}
else
return false;
}
string Rational::toString() const
{
stringstream ss;
ss << numerator;
if (denominator > 1)
ss << "/" << denominator;
return ss.str();
}
double Rational::doubleValue() const
{
return 1.0*getNumerator()/getDenominator();
}
Rational& Rational::operator+=(const Rational& secondRational)
{
*this = add(secondRational);
return*this;
}