2017-07-26 71 views
-7

我是c新手,請幫忙,這個答案總是零。爲什麼?而不是將KM轉換爲米或釐米(對於錯別字)。這個c代碼有什麼問題?答案始終爲零?

#include <stdio.h> 

int main() 
{ 
    float Km; 
    float metres; 
    float inches; 
    float centimetres; 

    printf("Welcome, please enter the distance in Km.\n"); 

    scanf("%f", &Km); 
    metres = Km * 1000; 
    centimetres = Km*100000; 
    inches = Km*25/1000000; 

    printf("Distance In Metres is:\n"); 
    printf("%f\n", &metres); 

    printf("Distance in Centimeters is:\n"); 
    printf("%f\n", &centimetres); 

    printf("Distance in Inches is:\n"); 
    printf("%f\n", &inches); 

    printf("bye\n"); 

    return 0; 
} 
+5

爲什麼要將變量的地址發送到printf語句> –

+2

英寸恰好是2.54釐米,而不是2.5英寸。而且我認爲你不應該把這個數字除以1000000。 – zwol

+2

Aside'inches = Km * 25/1000000;'better as'inches = centimeters * 2.54;' –

回答

2

printf函數寫入變量的值。和號運算符&將您的值轉換爲指針,這就是錯誤。不是打印變量的實際值,而是打印指針的地址內存。

閱讀關於printf函數的documentation。有關&*here的更多信息。

1

您正在打印位置的變量。計算很好,但實際上並沒有打印變量的值。您正在打印它在內存中的位置。

&運算符將給出變量的位置。您可以通過在printf語句去掉& S,修改你的程序,即這樣的:

printf("%f\n", &inches); 

變爲:

printf("%f\n", inches); 

此外,here是一個非常深入的printf()參考的鏈接;要了解更多關於指針的信息,可以去this page

+0

「如果要打印位置,...,請使用十進制或十六進制格式化程序(%d和%x」是不好的建議並且會損害良好的答案 - 建議刪除'%d'代表'int',不代表地址,要打印'void *',請使用'%p'。 – chux