2014-10-26 57 views
0

我做了极其简单的程序:问题在C简单使用printf和双号scanf函数的

#include <stdio.h> 
int main() 
{ 
    double x; 
    printf("Write your number \n"); 
    scanf ("%f", &x); 
    printf("You've written %f \n", x); 

    return 0; 
} 

而作为一个结果出现陌生的号码(无论什么X我给): “你'written written 83096261053132580000000000000000000000000000000000000000000

这是怎么回事?当我将所有数字改为'int'类型时,此程序正常工作。

+1

' “%F”'scanf函数的:使用' “%LF”'双。 – BLUEPIXY 2014-10-26 19:51:35

+0

'%f'代表'float';你已经给它一个'双'。 – 2014-10-26 19:51:40

回答

0

%f用于float类型。您应该使用%lf作为double(Long Float)。

+0

'scanf()''“%f”'与'float *'匹配,而不是'float'。在'printf()''“中,%f”'与'double',而不是'float'匹配。传递给variadic函数的'float'被转换为'double',因此'printf()'不会接收到'float'。 – chux 2014-10-26 23:04:21

+0

我当然会赞成Seprum。 – MightyMouse 2014-10-26 23:36:42

0

对于scanf和printf,您需要使用%lf

换句话说,这样的:

#include <stdio.h> 
int main() 
{ 
    double x; 
    printf("Write your number \n"); 
    scanf ("%lf", &x); 
    printf("You've written %lf \n", x); 

    return 0; 
} 
+0

使用'“%f”'对于OP作为'double x; ... printf(“你写过%f \ n”,x);'。 OP的问题仅在于'scanf()'。 – chux 2014-10-26 23:06:38

+0

显然你不能读取行之间的内容,因为OP不知道当需要将变量视为双精度时,双精度需要'lf'而不是'f'。 – MightyMouse 2014-10-26 23:09:52

+0

“双打要求lf而不是f”不正确。使用'scanf()',''%f''可以和'float *'一起工作,''%lf''可以''double *'。这个回答资产'%lf'是需要'printf()'的,这是不正确的。用'printf()',''%f''和''%lf“'工作。 – chux 2014-10-26 23:13:53

1

见当你打开了警告编译它会发生什么:

[email protected]:~/so$ gcc -Wall x.c -o x 
x.c: In function ‘main’: 
x.c:6:9: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat] 

变化%f%lfscanfprintf功能将正确地采取double

+0

更准确地说:'scanf()'不需要'double'。 'scanf(“%lf”,...)需要一个'double *'和'scanf(“%f”,...)'需要'float *'作为下一个参数。 – chux 2014-10-26 23:01:22

1

错误说明符scanf()

scanf()"%f"匹配float *,但编码通过了double *。改为使用"%lf"。代码的printf()没问题。见Correct format specifier for double in printf

double x; 
printf("Write your number \n"); 
// scanf ("%f", &x); 
scanf ("%lf", &x); 
printf("You've written %f \n", x); 

一个好的编译器应该警告你不正确的代码由@abligh的建议。启用所有警告或考虑一个新的编译器。


当扫描时,&x必须正确scanf()打印符匹配。

  • "%f"匹配的float *
  • "%lf"匹配double *

的使用printf()事情更容易。如果通过floatdouble作为可变参数函数,则float被提升为double

  • "%f""%lf"比赛一double
+1

'%lf'只打印自C99以来的双精度值;如果您在可能没有符合C99标准的C库的环境中工作,那么使用'%f'进行打印会增加您的“便携性”,并且不存在缺陷。 – 2014-10-26 23:19:34

+0

@Matt McNabb同意。注意:对'printf()'''%lf“'很好的使用是在选择的情况下使用与'scanf()'相同的格式字符串。对于过时15年以上的编译器存在可移植性的风险。 – chux 2014-10-26 23:27:33

+0

至少2011年MSVC仍然不支持'%zu'(尽管它们确实有'%lf') – 2014-10-26 23:30:00