在C中的另一个交换机中使用Switch语句

时间:2015-10-24 08:22:18

标签: c switch-statement

所以我试图制作一个程序主要是出于好奇和一点点我的学习!但我遇到了这个问题。当我尝试在另一个中使用switch语句时,如果我选择switch语句所在的情况,我的程序将变为默认值。

printf("Please enter the first character of the thing you want to get perimeter and area of off: ");
scanf_s("%c", &holder);

switch (toupper(holder))
{
case 'C':
    printf("Please enter the radius of the circle: ");
    scanf_s("%d", &a);
    if (a <= 0)
        printf("Please enter a positive radius!\n");
    else
    {
        perimeter = 2 * PI * a;
        area = PI * a * a;

        printf("Perimeter of the circle is %.2f\n", perimeter);
        printf("Area of the circle is %.2f\n", area);
    }
    break;
case 'R':
    printf("Please enter the two sides of the rectangle!\n");
    scanf_s("%d %d", &a, &b);

    if (a <= 0 || b <= 0)
        printf("Please enter positive numbers as sides values!\n");
    else
    {
        perimeter = a + a + b + b;
        area = a * b;

        printf("Perimeter of the rectangle is %.2f", perimeter);
        printf("Area of the rectangle is %.2f", area);
    }
    break;
case 'T':
    printf("Please enter a for calculation using 3 sides and b for 2 sides and the angle between them!");
    scanf_s("%c", &e);

    switch (e)
    {
    case 'a':
        printf("Please enter the three sides values!\n");
        scanf_s("%d %d %d", &a, &b, &c);

        if (a <= 0 || b <= 0 || c <= 0 || a >= b + c || b >= a + c || c >= a + b || a < abs(b - c) || b < abs(a - c) || c < abs(a - b))
            printf("Please enter viable side values!\n");
        else
        {
            perimeter = a + b + c;
            d = perimeter / 2;
            area = sqrt(d * (d - a) * (d - b) * (d - c));

            printf("Triangles perimeter is %2.f\n", perimeter);
            printf("Triangles area is %2.f\n", area);
        }
        break;
    case 'b':
        printf("Please enter 2 sides and the degree between them!\n");
        scanf_s("%d %d %d", &a, &b, &c);

        c1 = PI / 180 * c;
        perimeter = (a * a) + (b * b) - (2 * a * b * cos(c1));
        area = (1 / 2) * a * b * sin(c1);

        printf("Triangles perimeter is %2.f\n", perimeter);
        printf("Triangles area is %2.f\n", area);
        break;
    }
default:
    printf("Unknown character!\n");



}

system("pause");

}

1 个答案:

答案 0 :(得分:1)

你必须给出的第一个scanf输入是T\n(因为你给了T后跟输入键 - 在linux上是\n - 假设它是linux)

所以它目前在stdin缓冲区中不是一个而是两个字符。因此,当您扫描字符'e'时,它实际上读取'\n'而不是用户下一步输入的内容,因此在内部开关中进入默认情况。

编辑:由于内置交换机中没有默认情况,因此\n的情况不会在任何地方处理。这也意味着没有为外部开关执行break,因此将执行包括默认在内的所有后续情况,这就是您获得Unknown Character

的原因

因此,如果您确定总是按下回车键,则可以在取第二个字符之前执行getchar()

getchar(); //removes \n from stdin
scanf_s("%c", &e);