humanint 2017-03-21 09:02 采纳率: 100%
浏览 1029
已采纳

请问,c中的这段代码,scanf()读取数值后,缓冲区中剩下的\n到哪里去了?

如这个代码中的2个while
#include

#include

double twice(double x);
double half(double x);
double thrice(double x);
void showmenu(void);
#define NUM 4
int main(void)
{
double(*pf[NUM])(double) = { twice,half,thrice,sqrt };
double val;
double ans;
int sel;

puts("enter a number (negative to quit):");
while (scanf("%lf", &val) == 1 && val >= 0)      //用户输入数值后,缓冲区剩个\n
{                                                                       //这中间我并没有加入读掉\n的代码
    showmenu();
    while (scanf("%d",&sel)&&sel>=0&&sel<=3) //然后用户再次输入,第一个读取的不应该是\n吗?为何程序完美调试?
    {
        ans = (*pf[sel])(val);
        printf("answer=%f\n", ans);
        ans = pf[sel](val);
        printf("to repeat,answer=%f\n", ans);
        showmenu();
    }
    puts("enter next number (negative to quit)");
}
puts("bye");
getchar();
getchar();
return 0;

}

double twice(double x)
{
return 2.0*x;
}

double half(double x)
{
return x/2.0;
}

double thrice(double x)
{
return 3.0*x;
}

void showmenu(void)
{
puts("enter one pf the following choices:");
puts("0)double the value 1)halve the value");
puts("2)triple the value 3)squareroot the value");
puts("4)next number");
}

  • 写回答

2条回答 默认 最新

  • threenewbee 2017-03-21 08:59
    关注

    \n是作为界符被scanf识别掉的,所以此时不存在\n了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀