写一个C++代码:一个有理想(Rational)是由一个分子(numerator)和分母(denominator)组成的a/b形式的数。编写程序实现有理数如下功能: 包括三个文件Rational.h,Rational.cpp(30分),TestRationalClass .cpp(20分)。
时间: 2023-03-08 20:55:51 浏览: 259
#include <iostream>
using namespace std;//Rational.h
class Rational {
private:
int numerator;
int denominator;
public:
Rational(int num, int den);
int getNumerator();
int getDenominator();
void setNumerator(int num);
void setDenominator(int den);
void add(Rational r);
void subtract(Rational r);
void multiply(Rational r);
void divide(Rational r);
void print();
};//Rational.cpp
Rational::Rational(int num, int den){
numerator = num;
denominator = den;
}int Rational::getNumerator(){
return numerator;
}int Rational::getDenominator(){
return denominator;
}void Rational::setNumerator(int num){
numerator = num;
}void Rational::setDenominator(int den){
denominator = den;
}void Rational::add(Rational r){
numerator = numerator*r.denominator + denominator*r.numerator;
denominator = denominator*r.denominator;
}void Rational::subtract(Rational r){
numerator = numerator*r.denominator - denominator*r.numerator;
denominator = denominator*r.denominator;
}void Rational::multiply(Rational r){
numerator = numerator*r.numerator;
denominator = denominator*r.denominator;
}void Rational::divide(Rational r){
numerator = numerator*r.denominator;
denominator = denominator*r.numerator;
}void Rational::print(){
cout<<numerator<<"/"<<denominator<<endl;
}//TestRationalClass.cpp
int main(){
Rational r1 = Rational(1,2);
Rational r2 = Rational(2,3);
r1.add(r2);
r1.print();
r1.subtract(r2);
r1.print();
r1.multiply(r2);
r1.print();
r1.divide(r2);
r1.print();
return 0;
}
阅读全文