while 循环保持 运行 即使条件为假

while loop keeps running even when the condition is false

在给定的指令中,我将只使用 while 循环。目标是提示用户 select 可接受的输入。如果输入错误,程序会强制用户 select 进行适当的输入。该程序还保持 运行ning 直到用户通过 selecting 一个非常具体的输入选择存在,在我的例子中是大写或小写的“E”。

问题甚至在 select 大写或小写“E”之后,我的程序仍保持 运行ning。我使用“i”变量作为我的 while 循环的条件。例如,我将变量初始化为 2,并将我的 while 循环设置为 2,这意味着条件为真并且 while 循环将保持 运行ning。例如,仅当按下大写或小写字母“E”时,我才将“i”变量更改为 3。根据我的想法,这应该使循环为假,并且基本上不再 运行 循环,但我的循环保持 运行ning

#include<stdio.h>

int main()
{
    char selection;
    float length, width, area, base, height, apothem, side;
    int i=2;
    while (i=2)
    {
    printf("Press R to calculate the area of a rectangle\nPress T to calculate the area of a right angled triangle\nPress M to calculate the area of a polygon\nPress E to exit the program\n");
    scanf(" %c", &selection);
    switch (selection)
    {
    case 'R':
    case 'r':
        printf("Enter the length of the rectangle\n");
        scanf("%f", &length);
        printf("Enter the width of the rectangle\n");
        scanf("%f", &width);
        area=length*width;
        printf("The area of the rectangle is %f\n", area);
        break;
    case 'T':
    case 't':
        printf("Enter the base of the triangle\n");
        scanf("%f", &base);
        printf("Enter the height of the triangle\n");
        scanf("%f", &height);
        area=(0.5)*base*height;
        printf("The area of the triangle is %f\n", area);
        break;
    case 'M':
    case 'm':
        printf("Enter the length of one side of the polygon\n");
        scanf("%f", &length);
        printf("Enter the apothem of the polygon\n");
        scanf("%f", &apothem);
        printf("Enter the number of sides of the polygon\n");
        scanf("%f", &side);
        area=0.5*length*side*apothem;
        printf("The area of the polygon is %f\n", area);
        break;
    case 'E':
    case 'e':
        printf("You are exiting the program\n");
        i=3;
        break;
    default:
        printf("You have selected an invalid input\n");
        break;
    }
    }
    return 0;
}

程序有未定义的行为,因为在第一个 while 循环的条件下使用了未初始化的变量 selection

char selection;
float length, width, area, base, height, apothem, side;
while (!(selection == 'R' || selection == 'r') && !(selection == 'T' || selection == 't') && !(selection == 'M' || selection == 'm') && !(selection == 'E' || selection == 'e'))

你必须在循环之前初始化变量selection。例如,您可以通过以下方式做到这一点

char selection = '[=11=]';

而while循环的条件应该只有这个表达式

while (!(selection == 'E' || selection == 'e') )

在 switch 语句中检查所有其他输入值。

而不是这个调用

scanf("%c", &selection);

使用

scanf(" %c", &selection);
      ^^^^ 

否则也会输入白色 space 字符,例如换行符 '\n' 也会被输入。

并删除这些多余的调用

getchar();

您的原始代码可以工作,但您只需要在 while 条件下将符号 = 更改为 ==。