gpt4 book ai didi

c - 如何停止无限循环?

转载 作者:太空狗 更新时间:2023-10-29 15:51:24 25 4
gpt4 key购买 nike

我正在编写一个程序,该程序将计算三角形或正方形的面积,然后提示用户是否要计算另一个。我已经让代码工作到可以计算任一形状的面积的程度,但随后不会继续执行其余代码。例如,选择正方形,计算面积,然后返回正方形边的提示。我假设它又是 while 永远循环,但不知道如何阻止循环无休止地继续下去。

这是我的代码:

 #include<stdio.h>
#include<math.h>

int main(void)

{
float sq_side, tri_base, tri_height, Area;
char shape, cont = 'Y';

printf("Please select the type of shape you desire to calculate the area for:\n");
printf(" \n");
printf(" Square = S Triangle = T \n");
printf(" ------- x \n");
printf(" : : x x \n");
printf(" : : x x \n");
printf(" ------- xxxxxxx \n");
printf(" \n");
printf("Please select either S or T:");
scanf("%c", &shape);
while (cont != 'n' && cont != 'N')

if (shape == 'S' || shape == 's')
{
printf("What is the length of the sides of the square?:\n");
scanf("%f", &sq_side);

Area = pow(sq_side,2);

printf("The area of the square is %.2f.\n", Area);
}

else if (shape == 'T' || shape == 't')
{
printf("What is the length of the base of the triangle?:\n");
scanf("%f", &tri_base);
printf("What is the height of the triangle?:\n");
scanf("%f", &tri_height);

Area = 0.5 * tri_base * tri_height;

printf("The area of the triangle is %.2f.\n", Area);
}

else
{
printf("Error: You have select an incorrect option.");
}

printf("Do you wish to calculate a new shape?");
fflush(stdin);
scanf("%c", &cont);

return(0);

}

最佳答案

您缺少大括号。结果是只有 if 语句(包括 else if 链)实际上在循环体中。 printf(及更高版本)不是此复合语句的一部分。

 while (cont != 'n' && cont != 'N')
{
if (shape == 'S' || shape == 's')
{
printf("What is the length of the sides of the square?:\n");
scanf("%f", &sq_side);

Area = pow(sq_side,2);

printf("The area of the square is %.2f.\n", Area);
}

else if (shape == 'T' || shape == 't')
{
printf("What is the length of the base of the triangle?:\n");
scanf("%f", &tri_base);
printf("What is the height of the triangle?:\n");
scanf("%f", &tri_height);

Area = 0.5 * tri_base * tri_height;

printf("The area of the triangle is %.2f.\n", Area);
}

else
{
printf("Error: You have select an incorrect option.");
}

printf("Do you wish to calculate a new shape?");
fflush(stdin);
scanf("%c", &cont);
}

关于c - 如何停止无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3714269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com