简体   繁体   English

简单地在C中使用printf和doublef的scanf的问题

[英]Problems with simple use of printf and scanf of double numbers in C

I've made extremely easy program: 我做了一个非常简单的程序:

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

    return 0;
}

And as a result strange number appears (no matter what x I give): "You've written 83096261053132580000000000000000000000000000000000000000000 " 结果,出现一个奇怪的数字(无论我给x多少):“您已经写了83096261053132580000000000000000000000000000000000000000000

What's wrong with this? 这怎么了 This program works fine when I change all numbers into an 'int' type. 当我将所有数字都更改为“ int”类型时,此程序可以正常工作。

See what happens when you compile it with warnings enabled: 查看在启用警告的情况下进行编译时会发生什么:

amb@nimrod-ubuntu:~/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]

Change %f to %lf and the scanf and printf functions will correctly take a double . %f更改为%lfscanfprintf函数将正确地double

Wrong specifier for scanf() . scanf()说明符错误。

With scanf() , "%f" matches a float * , yet coded passed a double * . 使用scanf()"%f"匹配一个float * ,但编码传递了double * Use "%lf" instead. 使用"%lf"代替。 Code's printf() is fine. 代码的printf()很好。 See Correct format specifier for double in printf 请参阅正确格式说明符以在printf中使用double

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

A good compiler should have warned of your incorrect code as suggested by @abligh. 一个好的编译器应该已经警告您@abligh建议的错误代码。 Either enable all warnings or consider a new compiler. 启用所有警告或考虑使用新的编译器。


When scanning, the &x must match the proper scanf() print specifier. 扫描时, &x必须与正确的scanf()打印说明符匹配。

  • "%f" matches a float * "%f"匹配float *
  • "%lf" matches a double * "%lf"匹配double *

The using printf() things are easier. 使用printf()会更容易。 If a float or double is passed, being a variadic function, float is promoted to double . 如果传递了floatdouble值(作为可变函数),则float会提升为double

  • "%f" and "%lf" match a double "%f""%lf"匹配double "%lf"

%f is used for float type. %f用于float类型。 You should use %lf for double (Long Float). 您应该将%lf用作double (长浮点数)。

You need to use %lf for scanf and printf. 您需要对scanf和printf使用%lf

In other words, this: 换句话说,这是:

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

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM