当我声明int weight
然后输入双值165.1
时,第二个cin >> height;
不起作用,并且没有任何错误消息。你能告诉我为什么吗?
使用VS2010控制台应用程序。
#include <iostream>
using namespace std;
const double lbs_to_kg = 2.2046, inches_to_meter = 39.370;
int main()
{
int weight, height;
double kilograms, meters;
cout << "\nEnter weight in pounds: ";
cin >> weight;
kilograms = weight / lbs_to_kg;
cout << "\nEnter height in inches: ";
cin >> height;
meters = height / inches_to_meter;
cout << "\nYour BMI is approximately "
<< "\nbody fat ratio is "
<< kilograms / (meters * meters)
<< ". Under 25 is good."
<< endl;
}
output:
Enter weight in pounds: 165.1
Enter height in inches:
Your BMI is approximately
body fat ratio is 1.57219e-013. Under 25 is good.
答案 0 :(得分:13)
如果您尝试将cin
数据提取到无法保存的变量中,则数据会保留在输入流中,并且cin
会被标记为失败。您需要使用!cin
检查它是否失败,并使用cin.clear()
清除失败标志,以便您可以再次读取(将来的提取操作将自动失败,直到标志被清除)。您可以将数据提取到能够容纳它的另一个变量中,或者使用cin.ignore()
将其丢弃