c - Scanf 总是返回 0.000000

标签 c floating-point int printf scanf

我正在尝试编写一个简单的程序来计算体重指数,但无论我尝试什么,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;
}

最佳答案

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

所以改变这个:

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

关于c - Scanf 总是返回 0.000000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26834915/

相关文章:

c - 如何在 C 中对二维数组使用 double for 循环?

c++ - 在 C++ 中转换为字符串时限制 float 的小数位

java - "Incompatible operand types int and string"

ios - 在 Swift 中将字符转换为 Int

c - Getchar() 不断返回 1

c - 如何在 C 语言中组织一个项目中的多个主文件?

c - 下面的代码有什么问题

c++ - 在 C++ 中将 FP32 转换为 Bfloat16

sql-server - SQL Server Float 数据类型计算 vs decimal

c++ - 整数不等于它的值