这个c代码有什么问题?答案总是零?

时间:2017-07-26 18:49:18

标签: c debugging

我是c的新手,请帮助,答案总是为零。为什么?而不是将KM转换为米或厘米(抱歉打字错误);

#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;
}

2 个答案:

答案 0 :(得分:2)

printf函数写入变量的值。 &符运算符&将您的值转换为指针,这就是错误。您打印指针的地址存储器,而不是打印变量的实际值。

在printf函数上阅读documentation。有关&* here的更多信息。

答案 1 :(得分:1)

您正在打印变量的位置。计算很好,但您实际上并没有打印变量的值。您正在打印内存中的位置。

&运算符将给出变量的位置。您可以通过删除printf语句中的&来修复程序,即:

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

变为:

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

此外,here是指向非常深入的printf()引用的链接;要了解有关指针的更多信息,您可以转到this page

相关问题