本文介绍了问题:scanf用于双倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅以下代码:


/ * main.c * /


#include< stdio.h>


int main()

{

double d;

scanf("%f", & d);

printf("%g \ n",d);

}


问题是,无论我输入stdin(甚至是非法数据),

程序只打印一个似乎是来自原始内存的数据,

ie未初始化的内存(例如:5.35162e-315)。


如果我替换语句double d使用double d = 3.14,然后

我将始终得到输出3.14无论我输入什么(即使是非法数据)。


然后我可以得出scanf的结论。声明从来没有这样做.B
它的工作。我在3个编译器下尝试了这个,没有一个给出正确的结果




请给我一些解释。


谢谢。

Please see the following code:

/* main.c */

#include <stdio.h>

int main()
{
double d;
scanf("%f", &d);
printf("%g\n", d);
}

The problem is, whatever I input to stdin (even an illegal data), the
program just print a number that seems to be a data from "raw memory",
ie uninitialized memory (for example: "5.35162e-315").

And if I replace the statement "double d" with "double d = 3.14", then
I''ll always get the output "3.14" for whatever I input (even an
illegal data).

Then I may get the conclusion that the "scanf" statement never does
its job. And I have tried this under 3 compilers and none of them give
the right result.

Please give me some explanation about this.

Thanks.

推荐答案




如果您打开了编译器警告,您可能会得到

之类的东西


test.c:6:警告:浮动格式,双arg(arg 2)


双精度的正确转换说明符是%lf使用scanf时。另外,

应该从main返回一个值,一个回报(EXIT_SUCCESS);


-

Christopher Benson-Manica |我*应该*知道我在说什么 - 如果我

ataru(at)cyberspace.org |不,我需要知道。火焰欢迎。



If you had your compiler warnings turned on, you probably would have gotten
something like

test.c:6: warning: float format, double arg (arg 2)

The correct conversion specifier for doubles is %lf when using scanf. Also,
should return a value from main, a la

return( EXIT_SUCCESS );

--
Christopher Benson-Manica | I *should* know what I''m talking about - if I
ataru(at)cyberspace.org | don''t, I need to know. Flames welcome.





scanf("%lf"& d)


请参阅comp.lang.c中的问题12.13常见问题

问题(FAQ)列表



-
Er ********* @ sun.com




包含stdlib.h后的
当然;或者


返回0;


也没关系。

-

Irrwahn

(ir*******@freenet.de)



after inclusion of stdlib.h, of course; alternatively

return 0;

is fine, too.
--
Irrwahn
(ir*******@freenet.de)


这篇关于问题:scanf用于双倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 13:11