【问题标题】:how to use switch cases in a while loop如何在while循环中使用switch case
【发布时间】:2014-02-26 02:01:36
【问题描述】:

我担心的是程序只运行一次...... 在本作业中,我们将开发一个应用程序来计算面积和 几何形状的周长。首先要求用户输入一个字母代表 形状。我们用 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 0;,它将跳出您所在的任何函数。
  • 应该是scanf(" %c", &amp;choice);

标签: c


【解决方案1】:

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

return 0;

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

将其移到 while 循环下方:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-04
        • 2015-09-14
        • 2017-04-23
        • 1970-01-01
        相关资源
        最近更新 更多