Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- using namespace std;
- struct nr{
- int p;
- int q;
- };
- void affiche(nr nombre){
- if(nombre.q == 1){
- cout << nombre.p << endl;
- } else {
- cout << nombre.p << "/" << nombre.q << endl;
- }
- }
- int pgcd(int a, int b){
- int prev_u(1), prev_v(0), x(a), y(b), u(0), v(1);
- int new_u, new_v, q, r;
- /* Juste pour info. Normalement une telle fonction NE doit RIEN
- * afficher (« effet de bord ») !
- */
- while (y != 0) {
- q = x/y;
- r= x%y;
- x = y;
- y = r;
- new_u = prev_u - u * q;
- prev_u = u;
- u = new_u;
- new_v = prev_v - v * q;
- prev_v = v;
- v = new_v;
- /* Juste pour info. Normalement une telle fonction NE doit RIEN
- * afficher (« effet de bord ») !
- * L'affichage est ici approximatif. Pour faire mieux il faudrait
- * utiliser setw (présenté plus tard en cours)
- */
- }
- return x;
- }
- nr reduction(nr x){
- int co = pgcd(x.p,x.q);
- x.p /= co;
- x.q /= co;
- if(x.q < 0 and x.p > 0){x.p *= -1; x.q *= -1;}
- return x;
- }
- nr addition(nr r1, nr r2){
- nr a = {(r1.p*r2.q+r2.p*r1.q), (r1.q*r2.q)};
- return reduction(a);
- }
- nr soustraction(nr r1, nr r2){
- nr a = {(r1.p*r2.q-r2.p*r1.q), (r1.q*r2.q)};
- return reduction(a);
- }
- nr multiplication(nr r1, nr r2){
- nr a = {(r1.p*r2.p), (r1.q*r2.q)};
- return reduction(a);
- }
- nr division(nr r1, nr r2){
- if (r2.p == 0){
- throw string ("divided by 0");
- }
- if(r2.p < 0){
- nr a = {-(r1.p)*r2.q ,(r1.q*(-r2.p))};
- return reduction(a);
- } else {
- nr a = {r1.p*r2.q,(r1.q*(-r2.p))};
- return reduction(a);
- } // else {nr a = {0,0}; return a;}
- }
- int main()
- {
- nr a = {1, 2};
- nr b = {0, 5};
- affiche(a);
- affiche(b);
- try{
- affiche(division(a,b));
- }
- catch (string error){
- cerr << error << endl;
- return 1;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement