即使条件为false,while循环也将继续运行

时间:2020-10-24 10:26:34

标签: c loops while-loop switch-statement

在给定的指令中,我仅使用while循环。目的是提示用户选择可接受的输入。如果输入错误,程序将强制用户选择适当的输入。该程序还将一直运行,直到用户通过选择非常具体的输入(在我的情况下为大写或小写“ E”)选择存在为止。

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

#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;
}

2 个答案:

答案 0 :(得分:1)

程序具有未定义的行为,因为在第一个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 = '\0';

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

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

在switch语句中检查所有其他枚举值。

而不是此呼叫

scanf("%c", &selection);

使用

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

否则还将输入空白字符,例如也将输入换行符'\n'

并删除这些多余的呼叫

getchar();

答案 1 :(得分:1)

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