﻿ C++ exercises and solutions: Structure fractions

C++ exercises and solutions: Structure fractions

Exercise:  Write a C++ program to add two fractions and display the result fraction. Your program will prompt the user to input fraction 1 and fraction 2. The numerator and denominator of each fraction are input separately by space.  See the example output below. You will need to use a C++ structure to define a fraction. The structure has two members: numerator and denominator.

Enter fraction 1(numerator denominator): 1 2

Enter fraction 2(numerator denominator): 2 5

Result: 9/10

Solution:

#include<iostream>
#include<conio.h>
using namespace std;
struct Fract
{
int num;
int deno;

};

Fract sum(Fract,Fract);

int main()
{
int num1,deno1,num2,deno2;
cout<<"Enter fraction 1: numerator denominator:";
cin>>num1>>deno1;
cout<<"Enter fraction 2:numerator denominator:";
cin>>num2>>deno2;

Fract f1={num1, deno1};/* 1/2 */
Fract f2 ={num2, deno2};/* 2/5 */
Fract result = sum(f1, f2);//sum the fractions
cout<<result.num<<"/"<<result.deno;  //display the result

getch();
return 0;

}

Fract sum(Fract f1, Fract f2)
{
Fract result={(f1.num * f2.deno) + (f2.num * f1.deno), f1.deno * f2.deno};
return result;

} Kev花 yours a slightly better one but still both of them would act like fools if you give this values: 10000,10000 for the first fraction and 10001,10001 for the second one 2017-05-26 花I solved it in a slightly different way. The notable difference is how I convert them, which yields the result in its simplest form. In addition, I designed it so that you can input the fractions with a '/' in-between. #include using namespace std; struct fraction { int numerator; int denominator; }; fraction fraction1,fraction2,newfraction; int main() { cout<<"Enter fraction 1(Numerator/Operator): "; cin>>fraction1.numerator; cin.ignore(123,'/'); cin>>fraction1.denominator; cin.ignore(); cout<<"Enter fraction 2(Numerator/Operator): "; cin>>fraction2.numerator; cin.ignore(123,'/'); cin>>fraction2.denominator; cin.ignore(); int sum1,sum2; sum1=fraction1.denominator; sum2=fraction2.denominator; while (sum1!=sum2) { if (sum1