Sanee Reimoo - 4 months ago 43

C Question

`#include <stdio.h>`

#include <stdlib.h>

int main()

{

system("color f0");

int a,b,c,d,e,f,g,h,z;

printf("First numerator:");

scanf("%d",&a);

printf("First denominator:");

scanf("%d",&b);

printf("Second numerator:");

scanf("%d",&c);

printf("Second denominator:");

scanf("%d",&d);

a=a*d;

c=c*b;

e=a+c;

f=b*d;

printf("Simple form:%d/%d\n",e,f);

return 0;

}

Answer

You did some weird things with your code:

First, you ask a user for **two** nominators and **two** denominators.

So your lines

```
printf("Second numerator:");
scanf("%d",&c);
printf("Second denominator:");
scanf("%d",&d);
```

are superfluous and you may delete them.

Second, you lines

```
a=a*d;
c=c*b;
e=a+c;
f=b*d;
```

are *horrible* - a reader (and you) will be lost in your amount 1-letter names.

So why don't give a variable for a *nominator* the name `nominator`

and for a variable for a *denominator* the `denominator`

? And so on?

So replace your whole code with this one:

```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numerator, denominator, smaller, i;
system("color f0");
printf("Numerator : ");
scanf("%d",&numerator);
printf("Denominator: ");
scanf("%d",&denominator);
printf("\nOriginal fraction: %d/%d\n", numerator, denominator);
// Method: We get the smaller number from numerator and denominator
// and will try all numbers from it decreasing by 1 for common divisor
smaller = numerator < denominator ? numerator : denominator;
for (i = smaller; i > 1; --i)
if (numerator % i == 0 && denominator % i ==0)
{
numerator /= i;
denominator /= i;
break;
}
printf("Reduced fraction : %d/%d\n", numerator, denominator);
return 0;
}
```