簡體   English   中英

簡單地在C中使用printf和doublef的scanf的問題

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

我做了一個非常簡單的程序:

#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多少):“您已經寫了83096261053132580000000000000000000000000000000000000000000

這怎么了 當我將所有數字都更改為“ int”類型時,此程序可以正常工作。

查看在啟用警告的情況下進行編譯時會發生什么:

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]

%f更改為%lfscanfprintf函數將正確地double

scanf()說明符錯誤。

使用scanf()"%f"匹配一個float * ,但編碼傳遞了double * 使用"%lf"代替。 代碼的printf()很好。 請參閱正確格式說明符以在printf中使用double

 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 "%lf"

%f用於float類型。 您應該將%lf用作double (長浮點數)。

您需要對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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM