scanf问题阅读双倍 [英] scanf issue when reading double
问题描述
我的问题是一个奇怪的行为, scanf()
从用户输入中读取 double
。
我的代码:
int main(){
double radius = 0;
double pi = 3.14159;
scanf(%lf \\\
,& radius); //输入后,它继续等待...
radius =((radius * radius)* pi);
printf(A =%。4lf\\\
,radius);
return 0;
}
当我运行这个程序时,需要输入一个值,让我们假设 100.64
,正常行为是按回车,程序应该继续显示结果,但程序保持等待更多的输入。如果我输入0并再次按enter键,程序将继续正常。
> area.exe
100.64< - 在输入
0之后不进行此操作 - 需要输入另一个值,然后按enter键
A = 31819.3103< - 结果
为什么scanf不继续第一个输入?为什么需要更多?
Obs:在我的Linux中,这不会发生。
gcc --version
gcc(tdm64-1)4.9.2
在您的代码中,更改
scanf(%lf \\\
,& radius);
至
scanf(%lf,& radius);
否则,格式字符串空格
, scanf()
将表现如下(从 C11
引用,§7.21.6.2
,第5段)
由空白字符组成的指令通过读取输入执行到第一个非空格字符(保持未读),或直到没有更多的字符可以读取。
所以,提供非空格字符来结束扫描,您需要输入一个 0
(基本上是一个非空格字符) 。
请检查手册页更多细节。
I'm using MinGW on windows 7 to compile C files.
My problem is a strange behaviour with scanf()
to read double
s 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
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.
这篇关于scanf问题阅读双倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!