在C递归中使用char输入

时间:2019-04-11 15:17:47

标签: c

我试图在程序的一会儿递归中获取char变量的输入。 while语句的开头有3个主要输入,分别是charcharfloat。对于每个输入,我都将转换字符用作%*c%c,%*c%c,%f,但看起来好像不能正确使用输入值。然后,当我将输入的顺序更改为floatcharchar时,它可以完美工作。我在这里有什么想念的吗?

我还尝试将第一个字符输入的转换字符更改为%c,但是在循环的第一个循环之后它停止工作。还有其他方法可以在递归开始时使用char输入吗?我可以清楚地理解问题出在转换字符上。

我已经声明了上面所有的变量。 我只是想先获得LCH输入,然后程序停止工作。

while(CUN<=3)
    {

    TOTB1=0;
    TOTB2=0;
    //Inputs
    printf("Enter the Distance : ");
        scanf("%f",&DIS);
    printf("Are you a Loyalty Costomer(Y/N)? : ");
    scanf("%*c%c",&LCH);
    printf("Enter the Vehicle type: ");
        scanf("%*c%c",&CCH);


        //IF
        if(CCH=='A')
        {
            if(DIS>80)
            {
                TOTB1=(80*13000.00)+((DIS-80)*70.00);
            }
            else
            {
                TOTB1=DIS*13000.00;
            }
        }
        else if(CCH=='B')
        {
                     if(DIS>80)
                         {
                                 TOTB1=(80*15000.00)+((DIS-80)*100.00);
                         }
                         else
                         {
                                 TOTB1=DIS*15000.00;
                         }

        }
        else if(CCH=='C')
        {
            if(DIS>80)
            {
                         TOTB1=(80*7000.00)+((DIS-80)*80.00);
                        }
                        else
                        {
                                 TOTB1=DIS*7000.00;
                        }


        }
        else if(CCH=='D')
        {
            if(DIS>80)
                        {
                                 TOTB1=(80*8000.00)+((DIS-80)*80.00);
                        }
                        else
                        {
                                 TOTB1=DIS*8000.00;
                        }

        }
        printf("Bill Without Discount : %.2f\n",TOTB1);

        //Loyalty Discount
        if(LCH=='Y')
        {
            TOTB2=TOTB1-(TOTB1*0.1);
        }
        else if(LCH=='N')
        {
            TOTB2=TOTB1-(TOTB1*0.05);
        }

        //Calculate the Total Loop count Exit when CUN=3
        CUN=CUN+1;

        printf("Total Bill is %f\n",TOTB2);

        //Asking further
        printf("Do you want to continue for another vehicle : ");
        scanf("%*c%c",&AS);

        if(AS=='N')
        {
            break;
        }

    }

1 个答案:

答案 0 :(得分:3)

假设LCHCCH被定义为char,请更改格式字符串以使用换行符(\n)。

发件人:

scanf("%*c%c",&LCH);
printf("Enter the Vehicle type: ");
    scanf("%*c%c",&CCH);

收件人:

scanf(" %c",&LCH);
printf("Enter the Vehicle type: ");
    scanf(" %c",&CCH);
    //     ^  space prior to format specifier is to consume newline 
    //     which is inserted when user hits return key.

在定义变量时请考虑避免使用上限。它们通常用于#define常数和其他预处理器常数,以及一些标准struct名称,例如FILEcamelCaselowercase是更好的选择。