如何在while循环中使用switch case

时间:2014-02-26 02:01:36

标签: c

我担心的是程序只运行一次...... 在这项任务中,我们将开发一个应用程序来计算面积和 几何形状的周长。首先,要求用户输入代表的字母 形状。我们用C代表圆形,R代表矩形,S代表方形。 在用户选择形状后,程序会提示相应的形状 因此,形状的尺寸。例如,如果用户选择了正方形, 该计划将要求一方。如果它是一个圆圈,程序将询问半径。如果 它是一个矩形,它会要求长度和宽度。 收到适当的尺寸后,程序将计算面积和 请求形状的周长并将其打印在屏幕上。再一次,代码 会要求另一封信。如果用户输入“Q”,则程序终止。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float PI = 3.1415;
    char choice;
    float area, parameter;
    int radius, side, length, width;

    do{
        printf("Please enter a shape(C:Circle, S:Square, R:Rectangle, Q:Quiit> ");
        scanf("%s", &choice);

        switch(choice){
        case 'C':
            printf("Enter a radius of the circle: ");
            scanf("%d", &radius);
            area = (2*radius)*PI;
            parameter = 2*PI*radius;
            printf("The area of the circle is %.02f and parameter is %.02f", area, parameter);
        break;

        case 'S':
            printf("Enter the side of the square: ");
            scanf("%d", &side);
            area = side * side ;
            parameter = 4*side;
            printf("The area of the circle is %.02f and parameter is %.02f", area, parameter);
        break;

        case 'R':
            printf("Enter the width of the rectangle: ");
            scanf("%d", &width);
            printf("Enter the length of the rectangle: ");
            scanf("%d", &length);
            area = length*width;
            parameter = (2*length)+(2*width);
            printf("The area of the circle is %.02f and parameter is %.02f", area, parameter);
        break;

        case 'Q':
            printf("Thank and bye");
        break;

        default:
            printf("Invalid input");

    }
        return 0;
    } while (choice != 'Q');
}

3 个答案:

答案 0 :(得分:5)

它只运行一次,因为你在while循环中使用了return语句:

return 0;

main中的退货声明会在点击时结束您的计划。由于它是里面 while循环,它永远不会循环。第一次被击中它将结束程序,你将永远不会循环。

将其移至while循环下方:

} while (choice != 'Q');
return 0;

答案 1 :(得分:1)

您需要将return 0移到循环下方。

答案 2 :(得分:0)

你在while循环中有return 0。因此,一旦switch语句结束,程序返回0并且无法检查while循环条件。将return 0移出循环。

} while (choice != 'Q'); return 0;