(Modify) Modify Program 9.2 so that it continues to divide two numbers until the
ID: 3695207 • Letter: #
Question
(Modify) Modify Program 9.2 so that it continues to divide two numbers until the user enters the character q (as a numerator or denominator) to terminate program execution.
Here is Program 9.2 that needs to be modified in C++:
#include
using namespace std;
int main()
{
int numerator, denominator;
bool needDenominator = true;
cout << "Enter a numerator (whole number only): ";
cin >> numerator;
cout << "Enter a denominator (whole number only): ";
while (needDenominator)
{
cin >> denominator;
try
{
if (denominator == 0)
throw denominator; // an integer value is thrown
}
catch(int e)
{
cout << "A denominator value of " << e << " is invalid." << endl;
cout << "Please reenter the denominator (whole number only): ";
continue; // sends control back to the while statement
}
cout << numerator << '/' << denominator
<< " = " << double(numerator)/double(denominator) << endl;
needDenominator = false;
}
return 0;
}
Explanation / Answer
Hi I have added required code.
#include<iostream>
using namespace std;
int main()
{
int numerator, denominator ;
bool needDenominator = true;
while(true){
cout << "Enter a numerator (whole number only): ";
cin >> numerator;
if (cin.fail())
break;
cout << "Enter a denominator (whole number only): ";
while (needDenominator)
{
cin >> denominator;
if (cin.fail())
break;
try
{
if (denominator == 0)
throw denominator; // an integer value is thrown
}
catch(int e)
{
cout << "A denominator value of " << e << " is invalid." << endl;
cout << "Please reenter the denominator (whole number only): ";
continue; // sends control back to the while statement
}
cout << numerator << '/' << denominator
<< " = " << double(numerator)/double(denominator) << endl;
needDenominator = false;
}
if (cin.fail())
break;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.