A program will repeatedly ask the user to input a value to r
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 . . .
Solution
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
/**
* 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
*Of type: class std::logic_error
*/
int getDegrees(){
int angle;
cout << \"Enter an angle: \" << endl;
cin >> angle; //read an angle
if(angle < -359 || angle > 359) { //if the angle is <-359 or > 359 throw logic error
cout << \"Caught an exception: Out of range\ Of type: class std::logic_error\" << endl;
throw logic_error(\"Caught an exception: Out of range\ Of type: class std::logic_error\");
return NULL;
}else {
return angle; //else return the angle
}
}
int main()
{
while(true){ //read angle until user enters invalid anlge
int a = getDegrees();
if(a==NULL)
break;
else
cout << \"Rotating: \" << a << endl;
}
}
-----------------------------------------------
OUTPUT:
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

