Must be written in C++. You are developing a Fraction structure for Teacher’s Pe
ID: 3913696 • Letter: M
Question
Must be written in C++. You are developing a Fraction structure for Teacher’s Pet Software. The structure contains three public data fields for whole number, numerator, and denominator. Using the same structure, write the functions described below:
»An enter Fraction Value()function that declares a local Fraction object and prompts the user to enter values for the Fraction. Do not allow the user to enter a value of 0 for the denominator of any Fraction; continue to prompt the user for a denominator value until a valid one is entered. The function returns a data-filled Fraction object to the calling function.
Explanation / Answer
#include <iostream>
using namespace std;
struct Fraction // structure
{
int whole;
int numerator;
int denominator;
};
struct Fraction Value()
{
struct Fraction f;
int w,num,den;
// input whole part,numerator and denominator of the fraction
cout<<"Enter the whole part of fraction : ";
cin>>w;
cout<<" Enter the numerator of the fraction : ";
cin>>num;
do
{
cout<<" Enter the denominator of the fraction : ";// validate denominator
cin>>den;
}while(den == 0); // if denominator =0 keep on entering value for denominator
f.whole = w;
f.numerator = num;
f.denominator = den;
return f;// return fraction f
}
int main() {
struct Fraction f1;
f1 = Value();
cout<<" Fraction : "<< f1.whole<<" "<<f1.numerator<<"/"<<f1.denominator;
return 0;
}
Output:
Enter the whole part of fraction :3
Enter the numerator of the fraction :5
Enter the denominator of the fraction :0
Enter the denominator of the fraction :0
Enter the denominator of the fraction : 7
Fraction : 3 5/7
Do ask if any doubt. Please upvote.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.