C ++自动舍入

时间:2014-02-17 01:11:36

标签: c++ rounding

下面的代码会自动舍入输入。 我没有看到任何功能在任何地方围绕输入。 有人可以看看吗?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() 
 {
     string input = "";
     int weight = 0;
     int height = 0;
     int bmi = 0;
     while (true) 
     {
         cout << "Enter weight: ";
         getline(cin, input);
         // This code converts from string to number safely.
         stringstream myStream(input);
         if (myStream >> weight)
             break;
         cout << "Invalid number, please try again" << endl;
     }
     while (true) 
     {
         cout << "Enter height: " << endl;
         getline(cin, input);
         // This code converts from string to number safely.
         stringstream myStream(input);
         if (myStream >> height)
             break;
         cout << "Invalid number, please try again" << endl;
      }
      bmi = height * height;
      bmi = weight/bmi;
      if(bmi > 25) 
      {
          cout << "Overweight" << endl;
      } 
      else if(bmi < 18.5) 
      {
           cout << "Underweight" << endl;
      }
      else 
      {
           cout << "Normal weight" << endl;
      }
}

1 个答案:

答案 0 :(得分:11)

您遇到了一个名为integer truncation的问题。这可以通过使用浮动类型轻松修复,例如doublefloat