c - c中的“计算电路的面积和周长”程序......奇怪的输出

标签 c switch-statement scanf

我正在开发这个程序,它要求用户输入电路的半径,然后要求他们选择他想要计算的内容:面积、周长或圆柱体的体积。

#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/

相关文章:

c - 数组将数字列表中的相同数字存储两次

c posix 正则表达式验证输入 HH :MM:SS time string

c - C 结构的良好编码习惯?

javascript - 处理多个 "else if"语句。降低圈复杂度

c - sscanf - 带有可选/空格式说明符的解析帧

c++ - 如何使应用程序符号对库可见?

swift - 切换映射 : how to map enum to value without switch

javascript - switch 语句中的变量 case 列表

c - Lua 中是否有等效的 scanf 函数?

c - 为什么 c 中的 scanf() 函数中的多个参数会使应用程序崩溃?