我正在开发这个程序,它要求用户输入电路的半径,然后要求他们选择他想要计算的内容:面积、周长或圆柱体的体积。
#include <stdio.h>
int main(void)
{
float radius=0.0,height=0.0;
char choice,quit;
const float pi=3.1415658;
do
{
printf("Enter radius : \n");
scanf("%f",&radius);
printf("\n\nWhat do you want to calc.?\nArea of circuit --> press A\n"
"Circumference of circuit --> press C\nVolume of cylinder --> press V\nQuit --> Q\n");
scanf("%c",&choice);
switch (choice)
{
case 'A':
printf("Area = %.5f\n",radius*radius*pi);
break;
case 'C':
printf("Circumference = %.5f\n",2*radius*pi);
break;
case 'V':
printf("Enter Hight : \n");
scanf("%f",&height);
printf("Volume of cylinder = %.5f\n",radius*radius*pi*height);
break;
case 'Q':
quit='y';
break;
default:
printf("default!!\n");
break;
}
}while(quit != 'y');
return 0;
}
但是当我运行程序时
Enter radius : 3 What do you want to calc.? Area of circuit --> press A Circumference of circuit --> press C Volume of cylinder --> press V Quit --> Q /*here before I choose anything the next line appears, skipping reading the choice*/ default!! Enter radius :
那么为什么它会跳过读取用户的选择并直接跳转到默认值呢? 有什么问题吗??
最佳答案
这是因为当你使用scanf
读取半径时,你输入结束时按下的换行符还在输入缓冲区中。因此,当您稍后使用 scanf
读取一个字符时,它会读取该换行符。
简单的解决方案是告诉后者 scanf
跳过任何前导空格。这是通过在 scanf
格式代码中添加一个空格来完成的:
scanf(" %c", &choice);
/* ^ */
/* | */
/* Note space here */
关于c - c中的“计算电路的面积和周长”程序......奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20974283/