【问题标题】:Scanf always returning 0.000000Scanf 总是返回 0.000000
【发布时间】:2015-01-06 05:34:34
【问题描述】:

我正在尝试制作一个简单的程序来计算体重指数,但无论我尝试什么,scanf(s) 总是返回 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;
}

【问题讨论】:

  • 为什么不检查scanf的返回值?
  • 编译时出现警告。

标签: c floating-point int printf scanf


【解决方案1】:

如果您打印一个值,您不必打印地址!

所以改变这个:

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

【讨论】:

    【解决方案2】:

    嗯,你必须改变两件事。首先,将printf("%f", &amp;weight) 更改为printf("%f", weight)。并将scanf("%lf", &amp;weight) 更改为scanf("%f", &amp;weight) 将使您的程序正常。

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多