Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <stdbool.h>
  4. #include <assert.h>
  5.  
  6.  
  7. #define ABC(x) ((x) < 0 ? -(x) : (x))
  8.  
  9. typedef struct
  10. {
  11.     int32_t num, denom;
  12. } Ratio;
  13.  
  14. int32_t gcd(int32_t a, int32_t b){
  15.     int32_t t;
  16.     while (b != 0) {
  17.         t = b;
  18.         b = a % b;
  19.         a = t;
  20.     }
  21.     return a;
  22. }
  23.  
  24. //int32_t lcm(int32_t a, int32_t b){
  25. //   int32_t g = gcd(a, b);
  26. //   if(g == 0){
  27. //       return 1;
  28. //   }
  29. //   else {
  30. //       return (a * b) / g;
  31. //   }
  32. //}
  33.  
  34. Ratio Normalization(Ratio r){
  35.     int32_t a = gcd( ABC(r.num), ABC(r.denom) );
  36.  
  37.     r.denom /= a;
  38.     r.num   /= a;
  39.  
  40.     return r;
  41. }
  42.  
  43. void Input(Ratio *pR)
  44. {
  45.     assert(pR);
  46.  
  47.     printf("Enter ration(num denom): ");
  48.     scanf(" %d %d", &pR->num, &pR->denom);
  49.     while(pR->denom == 0){
  50.         printf("The denominator cannot be equal to 0, try again: ");
  51.         scanf(" %d %d", &pR->num, &pR->denom);
  52.     }
  53.  
  54.     if(pR->denom < 0){
  55.         pR->num   *= -1;
  56.         pR->denom *= -1;
  57.     }
  58.  
  59.     *pR = Normalization(*pR);
  60.  
  61. }
  62.  
  63. void Output(const Ratio r)
  64. {
  65.     printf("%d/%d\n", r.num, r.denom);
  66. }
  67.  
  68. int cmp(const Ratio left, const Ratio right) {
  69.     int32_t g = gcd(ABC(left.denom), ABC(right.denom));
  70.  
  71.     if((left.num * right.denom / g) < (right.num * left.denom / g )){
  72.         return -1;
  73.     }
  74.     else if((left.denom == right.denom) && (left.num && right.num)){
  75.         return 0;
  76.     }
  77.     else {
  78.         return 1;
  79.     }
  80. }
  81.  
  82. int main()
  83. {
  84.     Ratio r;
  85.     Input(&r);
  86.     Output(r);
  87.  
  88.     Ratio r2;
  89.     Input(&r2);
  90.     Output(r2);
  91.  
  92.     printf("cmp(r, r2): %d\n", cmp(r, r2));
  93.  
  94.  
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement