ppupil2

workshop 4B.2

Mar 5th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <conio.h>
  5.  
  6. void input(int *num, int *den); // input numerator (num) and denominator of a fraction (den)
  7. void display(int num, int den); // display the fraction
  8. void simplify(int *num, int *den); // simplify the fraction
  9.  
  10. int main() {
  11.     int n, d;
  12.     char choice;
  13.    
  14.     do {
  15.         printf("1. Input fraction\n\n");
  16.         input(&n, &d);
  17.         printf("\n2. Simplify fraction\n\n");
  18.         display(n, d);
  19.         printf("=\n");
  20.         simplify(&n, &d);
  21.         display(n, d);
  22.        
  23.         do {
  24.             fflush(stdin);
  25.             printf("Another run <y/n>? ");
  26.             scanf("%c", &choice);
  27.             if (choice != 'n' && choice != 'y') {
  28.                 printf("Invalid!\n");
  29.             }
  30.         } while (choice != 'n' && choice != 'y');
  31.        
  32.         if (choice == 'n') {
  33.             break; // ra khoi do-while(1)
  34.         }
  35.     } while (1);
  36.  
  37.     return(0);
  38. }
  39.  
  40. void input(int *num, int *den) {
  41.     char ch;
  42.    
  43.     /* input & check validation*/
  44.     while (1) // input numrator
  45.     {
  46.         printf("Enter numerator: ");
  47.         fflush(stdin);
  48.         scanf("%d%c", num, &ch);
  49.         if (ch == '\n') {
  50.             break;
  51.         }
  52.         else {
  53.             printf("Invalid numerator, please re-enter!\n");
  54.         }
  55.     }
  56.    
  57.     ch = '\0';
  58.     while (1) { // input denominator
  59.    
  60.         printf("Enter denominator: ");
  61.         fflush(stdin);
  62.         scanf("%d%c", den, &ch);
  63.         if (*den != 0 && ch == '\n') {
  64.             break;
  65.         }
  66.         else {
  67.             printf("Invalid denominator, please re-enter!\n");
  68.         }
  69.     }
  70. }
  71.  
  72. void display(int num, int den) {
  73.    
  74.     printf("%d/%d\n", num, den);
  75. }
  76.  
  77. int GCD(int a, int b){  /* giai thuat Euclid */
  78.     while (a!=0) {
  79.         if (a == b) {
  80.             break;
  81.         }
  82.         else {
  83.             if (a>b) {
  84.                 a = a-b;
  85.             }
  86.             else {
  87.                 b = b-a;
  88.             }
  89.         }
  90.     }
  91.     return a;
  92. }
  93.  
  94. void simplify(int *num, int *den) {
  95.     int a = GCD( abs(*num), abs(*den));
  96.    
  97.     *num /= a;
  98.     *den /= a;
  99. }
Add Comment
Please, Sign In to add comment