Scanf始终返回0.000000

时间:2014-11-10 00:13:38

标签: c floating-point int printf scanf

我试图制作一个简单的程序来计算体重指数,但无论我尝试什么,scanf都会返回0.00000。我到处搜索,尝试了很多东西, 谢谢大家。

#include <stdio.h>
#include <stdlib.h>


int main() {
    float height;
    float initialheight;
    float weight;
    float bmi;
    float nothing;

    printf("What's your weight? ");
    scanf("%lf", &weight);
    printf("%f", &weight);

    printf("What's your height? ");
    scanf("%lf", &initialheight);
    printf("%f", &initialheight);

    height = (initialheight * initialheight);
    printf("%f", &height);

    bmi = (weight / height);
    printf("Your BMI is ");
    printf("%f", &bmi);

    scanf("%f", nothing); //just to keep the program open
    return 0;
}

2 个答案:

答案 0 :(得分:2)

如果您打印一个值,则无需打印地址!

所以改变这个:

printf("%f", &weight);

到此:

printf("%f", weight);

这样你实际上打印了值

您还必须在scanf中将%lf更改为%f

所以你的程序应该是这样的:

#include <stdio.h>
#include <stdlib.h>

int main(){

    float height, initialheight, weight, bmi;

    printf("What's your weight?\n>");
    scanf(" %f", &weight);

    printf("%.2f\n\n", weight);

    printf("What's your height?\n>");
    scanf(" %f", &initialheight);

    printf("%.2f\n\n", initialheight);

    height = (initialheight * initialheight);
    bmi = (weight / height)*10000;

    printf("Your BMI is ");
    printf("%.2f\n\n", bmi);

    system("pause");
    return 0;

}

作为输入的示例:

70 and 175

结果/ BMI是:

22.86

旁注:

BMI = mass(kg) / (height(m) * height(m))

BMI = mass(lb) / (height(in) * height(in)) * 703

答案 1 :(得分:1)

你必须改变两件事。首先,将printf("%f", &weight)更改为printf("%f", weight)。此外,将scanf("%lf", &weight)更改为scanf("%f", &weight)也可以使您的计划更加完善。