精華區beta ck54th329 關於我們 聯絡資訊
---------------------------------rational.h---------------------------------- # ifndef RAITONAL_H # define RATIONAL_H using namespace std; class rational{ public: rational(); void set (int,int); double dbget (); void get (); int getn (); int getd (); private: int numerator; int denominator; }; int fhcm (int, int); rational set (int, int); rational add (rational,rational); rational product (rational,rational); rational divide (rational,rational); #endlif -------------------------------manipulate.cpp-------------------------------- #include <iostream> #include "rational.h" using namespace std; void main() { int f1n,f1d,f2n,f2d; rational f1,f2; cout<<"set f1-numerator:"; cin>>f1n; cout<<"set f1-denominator:"; cin>>f1d; cout<<"set f2-numerator:"; cin>>f2n; cout<<"set f2-denominator:"; cin>>f2d; f1.set(f1n,f1d); f2.set(f2n,f2d); cout<<"f1="; f1.get(); cout<<"\nf2="; f2.get(); } --------------------------------rational.cpp--------------------------------- #include <iostream> using namespace std; #include "rational.h" inline rational::rational (){set(1,1);}; void rational::set(int n, int d) { if (!d)cout<<"error:cn't set denominator 0"; else { int hcm=fhcm (n,d); numerator=n/hcm; denominator=d/hcm; } } double rational::dbget () { return numerator/denominator; } void rational::get () { cout<<numerator<<"/"<<denominator<<endl; } int rational::getn () { return numerator; } int rational::getd () { return denominator; } //-------------------------------------------------------------------------- int fhcm (int a,int b) { return (a==0)?b:fhcm(b%a,a); } rational add (rational a, rational b) { rational ans; int hcm=fhcm (a.getd(),b.getd()); int lcd=a.getd()*b.getd()/hcm; ans.set(a.getn()*lcd/a.getd()+b.getn()*lcd/b.getd(), lcd); return ans; } rational product (rational a, rational b) { rational ans; ans.set(a.getn()*b.getn(),a.getd()*b.getd()); return ans; } rational divide (rational a, rational b) { rational ans; ans.set(a.getn()*b.getd(),a.getd()*b.getn()); return ans; } -- 其實有一些改變 加上了一些功能 -- ※ 發信站: 批踢踢實業坊(ptt.csie.ntu.edu.tw) ◆ From: 210.85.118.7