/******************************************** * Elementary operations on fractions * * ----------------------------------------- * * This program allows user performing * * operations on fractions such as: * * 3/4 x 8/9 - 4/5 * * * * Sample run: * * * * 3 4 * * * * * 8 9 * * + * * -4 5 * * = * * Result is -2/15 * * ----------------------------------------- * * Ref.: "Mathématiques par l'informatique * * individuelle (1) par H. Lehning * * et D. Jakubowicz, Masson, Paris, * * 1982" [BIBLI 06]. * * * * C++ version by J-P Moreau. * * (www.jpmoreau.fr) * ********************************************/ #include #include //Labels e10,e20,fin int b,g,h,p,q,r,s,t,u; char cs[2]; void P300() { // substract r=-r; p=p*s+q*r; q=q*s; // common denominator for all operations } void P310() { // add p=p*s+q*r; q=q*s; // common denominator for all operations } void P330() { // Divide b=r; r=s; s=b; p=p*r; q=q*s; // common denominator for all operations } void P360() { // Multiply p=p*r; q=q*s; // common denominator for all operations } void P390() { // simplify result //Labels: e10,e20 t=p; u=q; e11: b=(int) (t-u*floor(t/u)); if (b==0) goto e21; t=u; u=b; goto e11; e21: p=p / u; q=q / u; if (q<0) {q=-q; p=-p;} } void main() { printf("\n"); //*** enter first fraction p/q (p=0 to exit) *** e10:printf(" ? "); scanf("%d %d",&p,&q); if (p==0 || q==0) goto fin; //*** enter operator: // = to view current result p/q // s to save current result // +,-,*,/ arithmetic operator //*** e20:printf(" ? "); scanf("%s",&cs[0]); if (cs[0]=='=') {printf(" Result is %d/%d\n",p,q); goto e20;} if (cs[0]=='s') {g=p; h=q; goto e10;} if (cs[0]=='q') goto fin; //*** enter next fraction r/s (if s=0, take current stored result) *** printf(" ? "); scanf("%d %d",&r,&s); if (r==0) goto fin; if (s==0) {r=g; s=h;} // computing result if (cs[0]=='+') P310(); if (cs[0]=='-') P300(); if (cs[0]=='*') P360(); if (cs[0]=='/') P330(); P390(); goto e20; fin: ; } // end of file fraction.cpp