Write a program which accepts 2 rational numbers from the keyboard., each in the
ID: 3575215 • Letter: W
Question
Write a program which accepts 2 rational numbers from the keyboard.,
each in the form a,b and c,d where a b is a/b and c d is c/d
example ENTER a rational number:
3 5
Enter a second number::
2 9
Check that the denominators are not =0
Write 4 functions called adds, subs, divs and mult. The main procedure calls
each function and passes the 2 rational numbers, and also 2 reference variables that will
hold the result of the computation.
The main program then produces output for each pair as follows:
a/b + c/d = x/y and also in double format n.nnn
a/b / c/d = x/y and also in double format n.nnn
example 5/6 + 2/3 = 10/6 1.666
5/6 / 2/3 = 15/12 1.25
extra credit for reducing fractions 2/4 --> 1/2
and simplifying 8/5 --> 1 3/5
Use the following data 3, 8 and 3, 5
5, 9 and 2, 3
Explanation / Answer
#include <iostream>
#include <iomanip>
using namespace std;
void adds(int a, int b, int c, int d, int *x, int *y){
*x = a * d + b * c;
*y = b * d;
}
void subs(int a, int b, int c, int d, int *x, int *y){
*x = a * d - b * c;
*y = b * d;
}
void divs(int a, int b, int c, int d, int *x, int *y){
*x = a * d;
*y = b * c;
}
void muls(int a, int b, int c, int d, int *x, int *y){
*x = a * b;
*y = b * d;
}
void print(int a, int b){
cout << a << "/" << b;
}
int main(){
cout << fixed << setprecision(3);
int a, b, c, d;
int x, y;
do{
cout << "Enter a rational number: ";
cin >> a >> b;
if(b == 0) cout << "Denominator cannot be 0 ";
}while(b == 0);
do{
cout << "Enter a second number: ";
cin >> c >> d;
if(d == 0) cout << "Denominator cannot be 0 ";
}while(d == 0);
adds(a, b, c, d, &x, &y);
print(a, b);
cout << " + ";
print(c, d);
cout << " = ";
print(x, y);
cout << " ";
subs(a, b, c, d, &x, &y);
print(a, b);
cout << " - ";
print(c, d);
cout << " = ";
print(x, y);
cout << " ";
divs(a, b, c, d, &x, &y);
print(a, b);
cout << " / ";
print(c, d);
cout << " = ";
print(x, y);
cout << " ";
muls(a, b, c, d, &x, &y);
print(a, b);
cout << " * ";
print(c, d);
cout << " = ";
print(x, y);
cout << " ";
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.