1

当我声明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.
4

1 回答 1

13

如果您尝试将cin数据提取到无法保存的变量中,则数据将留在输入流中并被cin标记为失败。您需要检查它是否失败!cin,并使用cin.clear()清除失败标志,以便您可以再次读取(未来的提取操作将自动失败,直到标志被清除)。您可以将数据提取到能够保存它的不同变量中,或者用于cin.ignore()丢弃它

于 2010-06-24T02:00:32.460 回答