c - 如何在 while 循环中使用 switch case

标签 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');
}

最佳答案

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

return 0;

main 中的 return 语句将在点击时结束您的程序。由于它位于 while 循环的内部,因此它永远不会循环。第一次被击中时,程序将结束,您将永远不会循环。

将其移至 while 循环下方:

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

关于c - 如何在 while 循环中使用 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22030215/

相关文章:

c - 如何开始使用 C 语言的 ICU

c - 如何将C中的字符转换为字符数组?

c - 如何在C中动态分配整数数组

c - 写入分配的二维数组

C: 简单复制输入 (getchar) 到输出 (printf) 返回额外的行

c - 直接给 C 指针赋值

c - C编译器中是否有 Debug模式编译标志的标准?

c - syslog.h中的 "0-big number"是什么意思?

c - xcode 恢复以前的版本?

C内存泄漏与双指针