为什么相同的程序在vs2017 和dev c++中跑出的结果不一样

为什么相同的程序在vs2017 和dev c++中跑出的结果不一样

问题描述:

#include

using std::cout;
using std::cin;
using std::endl;

int main()
{
cout << endl;
int n = 0;
double prev1 = 1.0;
double prev2 = 1.0;
double current = 0.0;
cout << "how many fib.nums to generate?";
while (!(cin>>n))
{
cin.clear();
cin.sync();
cout << "Please re-enter."< }
cout.precision(15);
while (n > 0)
{
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
--n;
}
cout << current << "\t";
cout << "ratio=" << prev1 / prev2 << endl;
cout << endl;
cout << "Press enter to exit.";
cin.ignore();
cin.ignore();
return 0;
}

 vs中输入字母会陷入死循环 另一个正常运行

要不改为
while (n)
{
if(cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please re-enter."
}
再试一试

当cin尝试将输入的字符读为int型数据失败后,会产生一个错误状态--cin.fail(),而要用cin读取输入流中的
数据,输入流必须处于无错误状态。因此,由于错误状态的存在,会一直执行while循环。

建议清除后你用break跳出while循环,否则无限循环

while (!(cin>>n) || cin.fail() )
{
cin.clear();
cin.sync();
cout << "Please re-enter."<
}
cout.precision(15);
或者改成这样,再试一试

因为你的while(!(cin》n))
判断为1、n为空值;2、n值错误;
您输入字母时判断为cin.fail(),清除后判断为空值,所以一直循环着。只有改为while(n){if(cin.fail()){...}...}判断方式,才能保证输入的值一定不是非空。

编译器不一样,有些代码编译器会给你优化。