Reputation: 147
I am a student and I am trying to make a very simple program that displays the quadrant of an angle that is entered in by the user.
However I want it to display that the angle is on the X axis or Y axis if the user enters the angle as 0,90,180 or 270.
I did put these 4 conditions in an if statement but the code is not terminating there and I am also getting the quadrant number corresponding to that angle. How do I terminate the code for those 4 angles after the if statement?
#include <iostream.h>
void main()
{
int angle;
cout<<"Enter an angle: ";
cin>>angle;
if (angle==90) cout<<"The angle lies on the positive Y axis";
else if (angle==0) cout<<"The angle lies on the positive X axis";
else if (angle==180) cout<<"The angle lies on the negative X axis";
else if (angle==270) cout<<"The angle lies on the negative Y axis";
angle=(angle/90)+1;
switch(angle)
{
case 1: cout<<"First Quadrant"; break;
case 2: cout<<"Second Quadrant"; break;
case 3: cout<<"Third Quadrant"; break;
case 4: cout<<"Fourth Quadrant"; break;
default: cout<<"That is not a valid angle.";
}
}
Upvotes: 2
Views: 1918
Reputation: 1952
if (angle%90==0)
{
switch(angle/90)
{
case 0: cout << "Angle lies on +X axis"; break;
case 1: cout << "Angle lies on +Y axis"; break;
case 2: cout << "Angle lies on -X axis"; break;
case 3: cout << "Angle lies on -Y axis"; break;
}
}
else
{
switch(angle/90)
{
case 0: cout << "First Quadrant"; break;
case 1: cout << "Second Quadrant"; break;
case 2: cout << "Third Quadrant"; break;
case 3: cout << "Fourth Quadrant"; break;
default: cout << "Invalid angle";
}
}
Upvotes: 0
Reputation: 21
The answer of Alex can solve your problem.
In addition to it, I think you may consider changing the type of object angle from int to double and adding more logic to handle the negative and none integer values.
Upvotes: 1
Reputation: 1845
Put it in a separate function that has early return:
string angleDescription(int angle)
{
if (angle < 0) return "Invalid input";
if (angle == 0) return "Positive X axis"
if (angle < 90) return "First quadrant";
// etc.
}
Upvotes: 0
Reputation: 6875
Modify a little like this for example:
int quadrant=(angle/90)+1;
if (angle==90) cout<<"The angle lies on the positive Y axis";
else if (angle==0) cout<<"The angle lies on the positive X axis";
else if (angle==180) cout<<"The angle lies on the negative X axis";
else if (angle==270) cout<<"The angle lies on the negative Y axis";
else
switch(quadrant)
{
case 1: cout<<"First Quadrant"; break;
case 2: cout<<"Second Quadrant"; break;
case 3: cout<<"Third Quadrant"; break;
case 4: cout<<"Fourth Quadrant"; break;
default: cout<<"That is not a valid angle.";
}
Upvotes: 2