scanf issue when reading double

前端 未结 2 419
不思量自难忘°
不思量自难忘° 2021-01-23 20:14

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 co

相关标签:
2条回答
  • 2021-01-23 20:57

    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.

    0 讨论(0)
  • 2021-01-23 21:02

    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.

    0 讨论(0)
提交回复
热议问题