Home > Back-end >  Adding fractions in C without using functions
Adding fractions in C without using functions

Time:03-23

I'm New to C and I want to know if there's a way to add two fractions by using the LCM, as i want to display the added fractions in reduced form. I also can't use functions or string or thing of that nature. I attempted to answer it using GCD but this isn't the assignment question so i could some help. Such as 3/8 5/12 = 19/24, i know this it the answer, i just don't know how to get c to display it

int main()

    int num1,denom1,num2,denom2,num3,denom3,GCD,i;
    while(denom1!=0 || denom2!=0)
    {
    cout<<"Enter Numerator of fraction one ";
    cin>>num1;
    cout<<"Enter Denominator of fraction one ";
    cin>>denom1;
    cout<<"Enter Numerator of fraction two ";
    cin>>num2;
    cout<<"Enter Denominator of fraction two ";
    cin>>denom2;
    num3 = (num1 * denom2)   (denom1 * num2);
    denom3 = denom1 * denom2; 
    cout<<"The answer is "<<num3<<"/"<<denom3;
    }
        if (denom3 == 0)
    {
      exit;
    }
    for (i = 1; i <= num3 && i <= denom3;   i)
    {
      if (num3 % i == 0 && denom3 % i == 0)
        GCD = i;
    }
    cout <<"\n The added fraction is " << num3/GCD << "/" << denom3/GCD;
    cout << endl;

    return 0;
}

CodePudding user response:

You probably want to implement something like

 class Fraction{
     private:
     int numerator;
     int denominator;

     public:
     Fraction (int n, int dn);
     void reduce ();
     Fraction add (Fraction a, Fraction b);
     Fraction subtract (Fraction a, Fraction b);
 }

CodePudding user response:

//i got this code, i bet it can be simplified, but i think you will understand it

#include //the library is iostream , but it isn´t showing

using namespace std;

int main() {

int tempNum , tempDenom; int denom1=8 , denom2=12 , denom3, num1=3 , num2=5, num3;

for(int i = 1 ; ;i ){ // this loop will work untill you find
multiplier for the first fraction

if ( (denom1 * i) % denom2 == 0){

denom3 = denom1 * i;
num1 = num1 * i;

 break;                     // when you find it, you will end the 
    }                           //loop with break

}

for(int i = 1 ; ;i ){ // this loop will work untill you find
multiplier for the second fraction

if ( (denom2 * i) % denom1 == 0){

num2 = num2 * i;
num3 = num1   num2;
 break;                     // when you find  it, you will end the 
    }                           loop with break

}

for (int i = num3 ; i > 1 ; i--){

tempNum = num3 % i;   //the % gives you the rest of the divison

tempDenom = denom3 % i;


if(tempNum == 0 && tempDenom == 0){

    num3 = num3 / i;
    denom3 = denom3 / i;

    
            break;       // you have simplified the fraction
}

}

    cout << "The result is : " << num3 << "/" << denom3;

}

  •  Tags:  
  • c
  • Related