在程序中一起使用If和Switch语句

时间:2015-08-30 13:42:37

标签: c++ if-statement switch-statement

我是学生,我正在尝试创建一个非常简单的程序,显示用户输入的角度的象限。

但是如果用户输入角度为0,90,180或270,我希望它显示角度在X轴或Y轴上。

我确实将这4个条件放在if语句中,但是代码没有终止,我也得到了与该角度相对应的象限数。如何在if语句之后终止这4个角度的代码?

#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.";

}
}

4 个答案:

答案 0 :(得分:2)

稍微修改一下,例如:

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.";

}

答案 1 :(得分:1)

Alex的答案可以解决您的问题。

除此之外,我认为您可以考虑将对象角度的类型从int更改为double,并添加更多逻辑来处理负值和非整数值。

答案 2 :(得分:0)

将它放在一个早期返回的单独函数中:

string angleDescription(int angle)
{
    if (angle <  0) return "Invalid input";
    if (angle == 0) return "Positive X axis"
    if (angle < 90) return "First quadrant";

    // etc.
}

答案 3 :(得分:0)

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";
    }
}