我认为错误在于这一行:
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);
}
最佳答案
您正在使用未初始化的 weight
和 height
:
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/