【发布时间】:2020-05-05 05:41:14
【问题描述】:
我的 BMI 计算存在问题。请告诉我哪里出错了,因为答案总是以 -nan(ind) 的形式返回。我确定问题出在计算本身,因为我删除了 displayFitnessResults 函数并简化了代码,但仍然出现错误。
#include<iostream>
#include <cmath>
using namespace std;
void getData(float weightP, float heightP)
{
cout << "Enter indivual's wight in kilograms and height in metres: ";
cin >> weightP >> heightP;
}
float calcBMI(float weightP, float heightP)
{
return weightP / (heightP * heightP);
}
void displayFitnessResults(float calcBMI)
{
if (calcBMI < 18.5)
{
cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is underweight";
}
else if (calcBMI >= 18.5 && calcBMI <= 24.9)
{
cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is healthy";
}
else if (calcBMI <= 25 && calcBMI >= 29.9)
{
cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is overweight";
}
else (calcBMI >= 30);
{
cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is obese";
}
}
int main()
{
float weight{}, height{}, BMI{};
cout.setf(ios::fixed);
cout.precision(2);
getData(weight, height);
BMI = calcBMI(weight, height);
displayFitnessResults(BMI);
return 0;
}
【问题讨论】:
-
除了 Remy 所说的,你应该更喜欢像这样声明你的变量
float weight, height, BMI;原因是,如果你这样做了,那么编译器会警告你你正在使用 未初始化的变量,这会(希望)让您意识到getData的问题。通过将变量初始化为无意义的值,您可以向编译器隐藏一个可能有用的警告。 -
calcBMI <= 25 && calcBMI >= 29.9永远不是true。是时候拿出那个调试器了。 -
代码中的第一个错误。如果
calcBMI是24.95会发生什么? (提示:什么都没有打印出来)。calcBMI==29.95时存在类似的错误。 -
代码审查:有一个函数以字符串形式返回
status。那么你的显示功能就是:cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is " << GetStatus(calcBMI); -
@Bathsheba 谢谢,但这些是作业中给出的参数:1. 低于 18.5 体重不足 2. 18.5-24.9 健康 3. 25.0-29.9 超重 4. 30.0 及以上 肥胖跨度>
标签: c++ calculation