【问题标题】:scanf issue when reading double读取双倍时的scanf问题
【发布时间】:2015-09-04 05:39:12
【问题描述】:

我在 windows 7 上使用 MinGW 来编译 C 文件。

我的问题是 scanf() 从用户输入中读取 doubles 的奇怪行为。

我的代码:

int main() {

   double radius = 0;
   double pi = 3.14159;

   scanf("%lf \n", &radius); // after the input, it continues waiting... 
   radius = ((radius * radius) * pi);
   printf("A=%.4lf\n", radius);  
   return 0;    
}

当我运行这个程序时,需要输入一个值,假设100.64,正常行为是按回车,程序应该继续并显示结果,但程序一直等待更多输入。如果我输入 0 并再次按回车,程序将继续正常运行。

>area.exe
100.64  <-- doesn't proceed after press enter
0 <-- needs input another value, then press enter
A=31819.3103 <-- the result

为什么 scanf 不继续第一个输入?为什么它需要更多?

Obs:在我的 Linux 中不会发生这种情况。

gcc --version
gcc (tdm64-1) 4.9.2

【问题讨论】:

  • 我可以建议int main() --> int main(void)吗?
  • @SouravGhosh 为什么?这种情况有区别吗?
  • 其实后者是C标准推荐的。

标签: c gcc double user-input scanf


【解决方案1】:

在你的代码中,改变

  scanf("%lf \n", &radius);

  scanf("%lf", &radius);

否则,对于具有whitespace 的格式字符串,scanf() 的行为如下(引自C11§7.21.6.2 章,第 5 段)

由空白字符组成的指令通过读取输入直到第一个非空白字符(仍然未读取)或直到无法读取更多字符来执行。

因此,要提供“非空白字符”来结束扫描,您需要输入一个0(基本上是一个非空白字符)。

详情请查看man page

【讨论】:

    【解决方案2】:

    对于稍微不同的问题,您有相同的解决方案(只是在变量类型方面)

    Why does scanf ask for input twice, but just in the first loop iteration only?

    当你在 scanf 中包含空格时

    程序将一直等待,直到您在其中输入空格或任何其他值,因此程序将照常继续,但无论如何都不会使用空格或您输入的任何值。

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多