Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- typedef struct
- {
- int n;
- int d;
- }rational;
- void doPositiveDenom ( rational *rat )
- {
- if ( rat->d < 0 )
- {
- rat->n *= -1;
- rat->d *= -1;
- }
- }
- void read ( rational *x )
- {
- while ( 1 )
- {
- scanf ( "%d %d", &x->n, &x->d );
- doPositiveDenom ( x );
- if ( x->d )
- break;
- printf ( "Denominator can not be 0.\nTry Again.\n" );
- }
- }
- int hcf ( int a, int b )
- {
- if ( a % b == 0 )
- return b;
- return hcf ( b, a % b );
- }
- void Simplify ( rational *x )
- {
- int gcd = hcf ( x->n, x->d );
- x->n /= gcd;
- x->d /= gcd;
- }
- void Add ( rational *x, rational y )
- {
- x->n = ( x->n * y.d ) + ( x->d * y.n );
- x->d = x->d * y.d;
- }
- void Sub ( rational *x, rational y )
- {
- x->n = ( x->n * y.d ) - ( x->d * y.n );
- x->d = x->d * y.d;
- }
- void Mul ( rational *x, rational y )
- {
- x->n *= y.n;
- x->d *= y.d;
- }
- void Div ( rational *x, rational y )
- {
- x->n *= y.d;
- x->d *= y.n;
- }
- void Reciprocal ( rational *x )
- {
- int t = x->n;
- x->n = x->d;
- x->d = t;
- }
- int Compare ( rational x, rational y )
- {
- int num_x = x.n * y.d, num_y = y.n * x.d;
- if ( num_x < num_y )
- return -1;
- else if ( num_x == num_y )
- return 0;
- else
- return 1;
- }
- void main ( )
- {
- int choice, compare;
- rational result, next;
- printf ( "Enter the first rational number (Numerator first)\n" );
- read ( &result );
- while ( 1 )
- {
- printf ( "1:\tAddition\n2:\tSubtraction\n3:\tMultiplication\n4:\tDivision\n5:\tCompare\n6:\tReciprocal\n7:\tDisplay\n0:\tEXIT\nCHOICE:\t" );
- scanf ( "%d", &choice );
- if ( !choice )
- break;
- if ( choice < 6 )
- {
- printf ( "\nEnter the next rational number (Numerator first)\n" );
- read ( &next );
- }
- switch ( choice )
- {
- case 1:
- Add ( &result, next );
- break;
- case 2:
- Sub ( &result, next );
- break;
- case 3:
- Mul ( &result, next );
- break;
- case 4:
- Div ( &result, next );
- break;
- case 5:
- compare = Compare ( result, next );
- break;
- case 6:
- Reciprocal ( &result );
- break;
- case 7:
- break;
- default:
- printf ( "INVALID CHOICE.\nTRY AGAIN.\n\n" );
- continue;
- }
- Simplify ( &result );
- printf ( "\n" );
- if ( choice == 5 )
- {
- if ( compare == -1 )
- printf ( "%d/%d > %d/%d\n\n", next.n, next.d, result.n, result.d );
- else if ( !compare )
- printf ( "%d/%d = %d/%d\n\n", result.n, result.d, next.n, next.d );
- else
- printf ( "%d/%d > %d/%d\n\n", result.n, result.d, next.n, next.d );
- }
- else
- printf ( "RESULT:\t\t%d/%d\n\n", result.n, result.d );
- }
- printf ( "RESULT:\t\t%d/%d\n", result.n, result.d );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement