【发布时间】:2021-02-07 05:57:03
【问题描述】:
在给定的指令中,我只使用 while 循环。目标是提示用户选择可接受的输入。如果输入错误,程序会强制用户选择合适的输入。该程序还会继续运行,直到用户通过选择一个非常具体的输入来选择存在,在我的例子中是大写或小写的“E”。
问题是即使选择大写或小写“E”后,我的程序仍然运行。我使用“i”变量作为我的 while 循环的条件。例如,我将变量初始化为 2,并将我的 while 循环设置为 2,这意味着条件为真并且 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;
}
【问题讨论】:
-
请比“不起作用”更好地描述问题。请给出准确的输入、预期结果和实际结果。第一个问题是
selection未初始化,因此在while条件中使用它会导致未定义行为。 -
仅供参考,
while (!(selection == 'R'....)问问自己selection的值是第一次 次评估循环条件。唯一正确的答案是“我不知道”,它与您的程序步调一致;它也没有。
标签: c loops while-loop switch-statement