scanf issue when reading double

2020-04-20 21:35发布

I'm using MinGW on windows 7 to compile C files.

My problem is a strange behaviour with scanf() to read doubles from user input.

My code:

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;    
}

When I run this program it's necessary input a value, let's suppose 100.64, the normal behaviour is press enter and the program should continue and show the result, but the program stays waiting for more input. If I type 0 and press enter again, the program continues normal.

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

Why scanf doesn't proceed with the first input? Why it needs more?

Obs: in my Linux this doesn't occur.

gcc --version
gcc (tdm64-1) 4.9.2

2条回答
姐就是有狂的资本
2楼-- · 2020-04-20 21:57

You have the same solution for a little bit different problem (just in type of variable)

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

When you include the whitespace in the scanf

The program will wait until you enter a blank space or any other value in it, so the program will continue as normal, but the blank space or any value that you entered will not be used anyway.

查看更多
▲ chillily
3楼-- · 2020-04-20 22:15

In your code, change

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

to

  scanf("%lf", &radius);

Otherwise, with a format string having whitespace, scanf() will behave as below (quoted from C11, chapter §7.21.6.2, paragraph 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.

So, to provide the "non-white-space character" to end the scanning, you need to input a 0 (basically, a non-whitespace character).

Please check the man page for more details.

查看更多
登录 后发表回答