gpt4 book ai didi

c++ - 关于C++中cin的一个问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:26 24 4
gpt4 key购买 nike

当我声明 int weight 然后输入 double 值 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.

最佳答案

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

关于c++ - 关于C++中cin的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com