Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <stdbool.h>
- #include <assert.h>
- #define ABC(x) ((x) < 0 ? -(x) : (x))
- typedef struct
- {
- int32_t num, denom;
- } Ratio;
- int32_t gcd(int32_t a, int32_t b){
- int32_t t;
- while (b != 0) {
- t = b;
- b = a % b;
- a = t;
- }
- return a;
- }
- //int32_t lcm(int32_t a, int32_t b){
- // int32_t g = gcd(a, b);
- // if(g == 0){
- // return 1;
- // }
- // else {
- // return (a * b) / g;
- // }
- //}
- Ratio Normalization(Ratio r){
- int32_t a = gcd( ABC(r.num), ABC(r.denom) );
- r.denom /= a;
- r.num /= a;
- return r;
- }
- void Input(Ratio *pR)
- {
- assert(pR);
- printf("Enter ration(num denom): ");
- scanf(" %d %d", &pR->num, &pR->denom);
- while(pR->denom == 0){
- printf("The denominator cannot be equal to 0, try again: ");
- scanf(" %d %d", &pR->num, &pR->denom);
- }
- if(pR->denom < 0){
- pR->num *= -1;
- pR->denom *= -1;
- }
- *pR = Normalization(*pR);
- }
- void Output(const Ratio r)
- {
- printf("%d/%d\n", r.num, r.denom);
- }
- int cmp(const Ratio left, const Ratio right) {
- int32_t g = gcd(ABC(left.denom), ABC(right.denom));
- if((left.num * right.denom / g) < (right.num * left.denom / g )){
- return -1;
- }
- else if((left.denom == right.denom) && (left.num && right.num)){
- return 0;
- }
- else {
- return 1;
- }
- }
- int main()
- {
- Ratio r;
- Input(&r);
- Output(r);
- Ratio r2;
- Input(&r2);
- Output(r2);
- printf("cmp(r, r2): %d\n", cmp(r, r2));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement