2011-10-15 29 views
0

我完全不知道爲什麼它返回2a=2b=2 ..2 + 2 =在C2(雙算術)

任何想法?

#include <stdlib.h> 

int main() 
{ 
    double a,b,c; 
    printf("a="); 
    scanf("%d", &a); 
    printf("b="); 
    scanf("%d", &b); 
    printf("c="); 
    scanf("%d", &c); 

    printf("x=%d", a+b); 

    return 0; 
} 
+2

您的問題已回答,但您還有其他錯誤。您包含'stdlib.h',但'printf'和'scanf'沒有在'stdlib.h'中定義。你需要'stdio.h'。順便說一句,你的編譯器確實應該發出所有這些問題的警告。你讀過它的輸出了嗎? –

回答

2

指定器"%d"期望一個整數,你傳遞一個double的地址。在scanf中使用錯誤的說明符會導致未定義的行爲。

此外,在printf中使用錯誤的說明符是同樣的事情。因爲printf需要可變數量的參數a + b這是一個double,不能轉換爲整數。

+0

它的工作。感謝幫助! – DavidMG

1

printf應該使用類似%f而不是%d。對於scanf也是一樣。

2

%d用於讀取整數,使用%f%lf用於float/double。

1

如果要接受浮點輸入,請使用scanf(和printf),其格式爲%lf,而不是%d(用於整數)。

當前程序的行爲是未定義的,因爲scanf調用正在將整數寫入浮點型變量。另外,您在程序頂部缺少include <stdio.h>。要捕捉這些錯誤,請打開C編譯器中的警告:

$ gcc so-scanf.c -Wall 
so-scanf.c: In function ‘main’: 
so-scanf.c:6:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration] 
so-scanf.c:6:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default] 
so-scanf.c:7:5: warning: implicit declaration of function ‘scanf’ [-Wimplicit-function-declaration] 
so-scanf.c:7:5: warning: incompatible implicit declaration of built-in function ‘scanf’ [enabled by default] 
so-scanf.c:7:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat] 
so-scanf.c:9:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat] 
so-scanf.c:11:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat] 
so-scanf.c:13:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat] 
+0

您需要%lf作爲scanf –

+0

@PaulR Oops的雙打。謝謝,修復。 – phihag