(Using C++) A program will repeatedly ask the user to input a value to rotate a
ID: 3932942 • Letter: #
Question
(Using C++)
A program will repeatedly ask the user to input a value to rotate a mechanical arm by a certain angle (in degrees). This angle must be between -360 and 360 to avoid excessive rotation. The program terminates when an improper angle is provided. Write this program, and use the following function declaration.
/** * Prompts the user to input a number of degrees * and returns the value * * If the user provides a value < 359 or > 359 a * std::logic_error exception is thrown and the * return value undefined. */ int getDegrees();
The output of the program should match the following:
Enter an angle: 20 Rotating: 20
Enter an angle: -15
Rotating: -15
Enter an angle: 354 Rotating: 354
Enter an angle: -360
Caught an exception: Out of range
Of type: class std::logic_error
Press any key to continue . . .
Explanation / Answer
Please follow the code and comments for description :
CODE :
#include <iostream> // required header files
#include <stdexcept>
using namespace std;
int getDegrees(); // function declaration
int getDegrees() { // function initialisation
int angle; // local varaibles
cout << "Enter an angle : "; // prompt for the data to be entered
cin >> angle; // get the data
try {
if((angle <= 360) && (angle >= -360)) { // check for the condition
return angle; // return the value if satisfied
} else {
throw logic_error("Caught an exception: Out of range Of type: class std::logic_error"); // else throw an exception
}
} catch(logic_error le) { // catch the error
cout << le.what() << endl; // print to console
exit(0); // exit the code
}
return 0;
}
int main() // driver method
{
int res = getDegrees(); // call the function
cout << "Rotating : " << res; // print the output
return 0;
}
OUTPUT :
Case 1 :
Enter an angle : 361
Caught an exception: Out of range
Of type: class std::logic_error
Case 2 :
Enter an angle : 345
Rotating : 345
Hope this is helpful.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.