c++ - 这个 BMI 计算器有什么问题?
问题描述
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double lbs;
double kg = lbs/2.205;
double feet;
double inches;
double height= ((feet * 12) + (inches))/39.37;
double bmi=(kg)/(height * height);
cout << "What is your weight (lbs)?" << endl;
cin >> lbs;
cout << "What is your height ? (feet only)" << endl;
cin >> feet;
cout << "What is your height ? (inches)" << endl;
cin >> inches;
cout << "Your BMI is : " << kg/(height*height);
}
最终输出为:inf。这意味着什么?
解决方案
考虑以下语句序列:
double lbs;
double kg = lbs/2.205; // lbs is uninitialized here, oops
cout << "What is your weight (lbs)?" << endl;
cin >> lbs;
您lbs
在从用户读取它之前使用它,事实上,在初始化它之前,它会调用未定义的行为。
您需要像这样重新排序语句:
double lbs;
cout << "What is your weight (lbs)?" << endl;
cin >> lbs;
double kg = lbs/2.205; // compute kg after reading in lbs
你也需要对其他变量做类似的事情。
推荐阅读
- javascript - 在新窗口中打开的 Web 资源中使用 Xrm.WebApi 方法
- java - Twincat ADS 事件驱动的读取在一段时间后停止工作(Java)
- yaml - 如何在 CloudWatch 警报中传递 EMR 集群 ID
- c++ - 如何删除选定的图形项组?
- deep-learning - 减小 fasttext bin 文件的大小
- javascript - 过滤包含 Javascript 中特定符号或单词的数组
- python - 在 Python 服务中使用 configparser 不会启动服务
- active-directory - 如何使用 Ldap 查询查找受信任的域组
- angularjs - 如何在 Ionic3 框架中获取选定的复选框 ID 和相应的文本框值
- reactjs - 使用导航从一个页面导航到另一个页面以响应本机