嘿伙计......再来一次新手:)我正在组合一个计算三角形或正方形区域的程序,然后提示用户是否希望计算另一个。我已经得到了代码,它将计算任一形状的区域,但不会继续其余的代码。例如,选择方形,计算面积,然后返回到方形边的提示。我假设它永远是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);
}
答案 0 :(得分:8)
你缺少花括号。结果是只有if语句(包括else ifs链)实际上在循环体中。 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);
}
答案 1 :(得分:3)
循环时没有括号。所以if elseif else块之外的代码没有被调用。
目前您的代码转换为
while (cont != 'n' && cont != 'N')
{
if (shape == 'S' || shape == 's')
{}
else if (shape == 'T' || shape == 't')
{}
else
{}
}
printf("Do you wish to calculate a new shape?");
fflush(stdin);
scanf("%c", &cont);
何时需要
while (cont != 'n' && cont != 'N')
{
if (shape == 'S' || shape == 's')
{}
else if (shape == 'T' || shape == 't')
{}
else
{}
printf("Do you wish to calculate a new shape?");
fflush(stdin);
scanf("%c", &cont);
}
请记住,如果在控件结构中不包含花括号,它只会调用下一个语句,在您的情况下是一系列嵌套的if-else if语句。
希望它有所帮助 - Val