Пока помогите - PullRequest
       3

Пока помогите

3 голосов
/ 15 сентября 2010

Эй, ребята ... опять новичок :) Я собираю программу, которая вычислит площадь треугольника или квадрата и затем подскажет пользователю, желают ли они вычислить другой.У меня есть код, работающий до такой степени, что он будет вычислять площадь любой фигуры, но затем не продолжит работу с остальным кодом.Например, если выбран квадрат, вычисляется площадь, а затем возвращается к подсказке для стороны квадрата.Я предполагаю, что это снова время цикла навсегда, но я не знаю, как остановить цикл бесконечно.

Вот мой код:

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

 }

Ответы [ 2 ]

8 голосов
/ 15 сентября 2010

Вам не хватает фигурных скобок.В результате в теле цикла фактически находился только оператор if (который включает в себя цепочку других 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);
}   
3 голосов
/ 15 сентября 2010

Там нет скобок для вас, пока цикл.Таким образом, код вне вашего блока if elseif не вызывается.

в настоящее время ваш код преобразуется в

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...