阅读双倍时的 scanf 问题

scanf issue when reading double

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

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

我的代码:

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

在您的代码中,更改

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

  scanf("%lf", &radius);

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

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

因此,要提供"non-white-space character"来结束扫描,您需要输入一个0(基本上是一个非空白字符)。

请查看man page了解更多详情。

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

当你在 scanf

中包含白色space

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