#ifndef RationalNums_H #define RationalNums_H #include <iostream> #include <cstring> using namespace std; class RationalNums// define the class { int numerator,denominatore; public: RationalNums(int , int); RationalNums(int); RationalNums(); int get_numerator(); void set_numerator(int); int get_denominatore(); void set_denominatore(int); void printFraction(); bool chkEquality(int, int); private: void reduction(int &a, int &b); }; #endif |
#include "RationalNums.h" //constructors RationalNums::RationalNums(int _numerator, int _denominatore) { numerator=_numerator; denominatore=_denominatore; } RationalNums::RationalNums(int _numerator) { numerator=_numerator; denominatore=0; } RationalNums::RationalNums() { numerator=0; denominatore=0; } // get & set functions int get_numerator() { return numerator; } void set_numerator(int _numerator) { numerator=_numerator; } int get_denominatore() { return denominatore; } void set_denominatore(int _denominatore) { denominatore=_denominatore; } //print the class values void printFraction() { cout<<numerator<<"/"<<denominatore<<endl; } //compare between 2 rational numbers bool chkEquality(int otherNumerator, int otherDenominatore) { reduction(otherNumerator,otherDenominatore); reduction(numerator,denominatore); if(numerator==otherNumerator && denominatore==otherDenominatore) return true; else return false; } //reduce the fraction void reduction(int &a, int &b) { int lower; if (a>b) lower=b; else lower=a; for(int i=lower; i>1; --i) { if ((a % i==0) && (b % i ==0)) { a/=i; b/=i; } } } |
#include <iostream> #include <cstring> #include "RationalNums.h" using namespace std; bool validation(char *a, int &x, int &y) { int z=0, mone=0, pos, result=true; char temp[15]={NULL}; while(a[z]!=0 && a[z]!='/') { if (a[z]<'0' || a[z]>'9') result=false; mone++; z++; } if (mone==0) result=false; pos=mone; if (a[z]!='/') result=false; z++; mone=0; while(a[z]!=0 && a[z]!='/') { if (a[z]<'0' || a[z]>'9') result=false; mone++; z++; } if (mone==0) result=false; if (result) { strncpy(temp, a, pos); x=atoi(temp); // if left side is valid strncpy(temp, a+pos,mone); y=atoi(temp); } else cout<<"ERROR"; cout<<"y:"<<y; if (y==0)// to prevent division by zero { cout<<"ERROR"; result=false; } return result; } int main() { int x,y; char a[15],b[15]; RationalNums rational; cout<<"enter two rational numbers:\n"; //get first rational number and set in the class object cin>>a; //cin>>b; if (validation(a,x,y)) { rational.set_numerator(x); rational.set_denominatore(y); // get second rational number cin>>b; if (validation(b,x,y)) { ////comapre the 2 rational numbers if(rational.chkEquality(x,y)) cout<<"equal"; else cout<<"different"; cout<<endl; } } system("pause"); return 0; } |
|
|
|
|