我的开关盒有什么问题?

时间:2011-01-24 19:56:09

标签: c++ c

它会自动执行默认设置而不是我的任何情况。知道我做错了吗?

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

int main ()
{

    float x,y,z,p,a,h;
    int d;

    printf ("\n This program calculates Perimeter, Area, or Hypotenuse of a right triangle based on user choice\n\n\n\n");

    /* Prompt user to select which calculation is to be performed */

    printf ("If you would like to calculate Perimeter, type P\nIf you would like to calculate Area, type A\nIf you would like to calculate 
    Hypotenuse, type H\n\n") ;

    scanf ("%f,%f,%f",&p,&a,&h);


    switch(d)
    {
        case('p'):
            printf("/n You have chosen to do a perimeter calculation/n");
            printf("/n Input the two side lengths of the right triangle separated by a space/n");

            scanf("%f,%f",&x,&y);
            z = pow (x,2) + pow (y,2);
            p = x + y + z;

            printf("\nLength of side A entered=%f\n",x);
            printf("\nLength of side B entered=%f\n",y);
            printf("\nCalculated Perimeter=%f\n",p);

            break;


        case('a'):
            printf("/n You have chosen to do an area calculation/n");
            printf("/n Input the two side lengths of the right triangle separated by a space/n");

            scanf("%f,%f",&x,&y);
            z = pow(x,2) + pow(y,2);
            p = x + y + z;
            a = (x * y) / 2;

            printf("\nLength of side A entered=%f\n",x);
            printf("\nLength of side B entered=%f\n",y);
            printf("\nCalculated area=%f\n",a);

            break;


        case('h'):

            printf("/n You have chosen to do a hypotenuse calculation/n");
            printf("/n Input the two side lengths of the right triangle separated by a space/n");

            scanf("%f,%f",&x,&y);
            z = pow (x,2) + pow (y,2);

            printf("\nLength of side A entered=%f\n",x);
            printf("\nLength of side B entered=%f\n",y);
            printf("\nCalculated Hypotenuse=%f\n",z);

            break;

            default:

                printf("/n wow...how did that even happen. Please put in a valid letter next time. /n");
    }
}

4 个答案:

答案 0 :(得分:8)

您永远不会将任何值分配给d,因此它未初始化。

答案 1 :(得分:3)

看起来像你的scanf()调用:

scanf ("%f,%f,%f",&p,&a,&h);

应该是:

 scanf ("%c",&d);

为什么你会认为接受三个浮动输入对于提示的文本是有意义的??

但是这样做会导致后续输入调用出现问题,所以你应该做的是:

scanf ("%c",&d);
while( d != '\n' && getchar() != '\n' ) 
{
    // do nothing but flush to the end of the input line
}

答案 2 :(得分:2)

你永远不会设置d的值,但你仍然在开关中使用它。

答案 3 :(得分:0)

您永远不会分配变量d

相关问题