-3
#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;
}

This is my code i want to reduce that simple fraction to the lowest possible but without using maths library

SIGSTACKFAULT
  • 919
  • 1
  • 12
  • 31

2 Answers2

2

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 of 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;
}
MarianD
  • 13,096
  • 12
  • 42
  • 54
0

Stack overflow != /r/homeworkhelp

A psuedocode algorithm:

get a fraction in the form of a/b

while a/b is not in lowest terms:
    find a common divisor, k
    divide a by k  
    divide b by k
end while

to check if something is lowest terms:

if A == B:
    [not lowest terms]
if A is a multiple of B:
    [not lowest terms]
if there is a common divisor: // this catches the first two.
    [not lowest terms]
else:
    [lowest terms]

I'm going to leave the divisor-finder to you, otherwise it would be too easy.

SIGSTACKFAULT
  • 919
  • 1
  • 12
  • 31