c - 程序返回信息?

标签 c floating-point

我认为错误在于这一行:

float bmi = weight * 703 / pow(height, 2.0); // user inputs weight and height and the bmi should be calculated.

问题是,我创建了一种模拟程序,其中已经输入了值,一切都很好。但是当我使用 scanf() 让用户输入那些相同的值时,它不起作用。

#include <stdio.h>
#include <math.h>

int main ()
{
    float weight = 105, height = 63;
    float bmi;
    bmi = weight * 703 / pow(height, 2.0);
    printf("%f\n", bmi);
}

体重和高度都是 float 。当我尝试打印 bmi 时,我得到了“inf”。

** 编辑以显示输入函数和打印语句。

 printf("Weight? ");
    scanf("%f", &weight);

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

另一个输入语句本质上是用高度代替重量。

编辑:这是完整的代码

#include <stdio.h>
#include <math.h>

int main ()
{
    float weight, height;
    float bmi = weight * 703 / pow(height, 2.0);

    printf("Height? ");
    scanf("%f", &height);

    printf("Weight? ");
    scanf("%f", &weight);

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

    printf("%f\n", height);
    printf("%f\n", weight);


}

最佳答案

您正在使用未初始化的 weightheight:

   float weight, height;
   float bmi = weight * 703 / pow(height, 2.0);

这是未定义的行为,这就是为什么你得到 inf,在我的例子中我得到 0.00,但在 UB 下任何事情都可能发生。

更改为

#include <stdio.h>
#include <math.h>

int main(void)
{
    float weight, height;
    float bmi;

    printf("Height? ");
    scanf("%f", &height);

    printf("Weight? ");
    scanf("%f", &weight);

    bmi = weight * 703 / pow(height, 2.0);
    printf("Your BMI is calculated at %.2f.\n", bmi);

    printf("%f\n", height);
    printf("%f\n", weight);
    return 0;
}

关于c - 程序返回信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25577846/

相关文章:

c - 来自 epoll_wait 的 epoll 事件顺序

python - 将字符串解析为 float 的 python 标准是什么?

c - 重新排列方程式

javascript - JavaScript 中的精确浮点运算

c - 简单地创建一个数据结构,它怎么会发生段错误?

c - C 中的 pthread,不兼容的类型

c - fftw3 逆变换不起作用

c - 十六进制浮点常量

c++ - 如何使用cout以全精度打印 double 值?

c - C 中的多重赋值?