首页 > 解决方案 > 这个 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。这意味着什么?

标签: c++

解决方案


考虑以下语句序列:

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

你也需要对其他变量做类似的事情。


推荐阅读