我试图在程序的 while 递归中获取 char
变量的输入。 while
语句开头有3个主要输入,分别是char
、char
、float
。我将转换字符用作每个输入的 %*c%c,%*c%c,%f
但看起来它没有正确获取输入值。然后,当我将输入的顺序更改为 float
、char
、char
时,它会完美运行。我在这里遗漏了什么吗?
我还尝试将第一个 char 输入的转换字符更改为 %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;
}
}
最佳答案
假设 LCH
和 CCH
定义为 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
名称,例如 FILE
。 camelCase
或 lowercase
是更好的选择。
关于c - 在 C 递归中使用 char 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55635943/