我的C++在Xcode代码停止工作正常
问题描述:
我有这样的代码:我的C++在Xcode代码停止工作正常
#include <iostream>
using namespace std;
double sqrt(double n)
{
double x;
double y = 2; //first guess is half of the given number
for (int i = 0; i<50; i++)
{
if (n>0)
{
x = n/y;
y = (x + y)/2;
}
if (n==0)
{
return 0;
}
}
return y;
}
int main()
{
cout << "Square Root Function" << endl;
double z=0;
while (true)
{
cout << "Enter a number = ";
cin >> z;
if (z<0)
{
cout<<"enter a positive number"<<endl;
continue;
}
cout <<"the square root is "<< sqrt(z) << endl;
}
return 0;
}
,它会显示这样的结果:
Square Root Function
Enter a number = 12
the square root is: 3.4641
但现在的代码显示这些结果:
Square Root Function
1 //my input
Enter a number = the square root is 1
2 //my input
Enter a number = the square root is 1.41421
似乎只有在字符串后面添加了endl时,cout才会首先显示。这最近刚刚开始发生。有没有办法可以解决这个问题,以显示正确的输出?
答
std::cout
使用缓冲输出,应该始终被冲洗。您可以通过使用std::cout.flush()
或std::cout << std::flush
来实现此目的。
您还可以使用std::cout << std::endl
,这将写入一个换行符,然后刷新,这就是你的代码显示了这种现象的原因。
更改int main()
到
int main(){
std::cout << "Square Root Function" << std::endl;
double z=0;
while (true){
std::cout << "Enter a number = " << std::flush
/*^^^^^^^^^^*/
std::cin >> z;
if (z<0){
std::cout << "enter a positive number" << std::endl;
continue;
}
std::cout << "the square root is " << sqrt(z) << std::endl;
}
}
编辑:Xcode的问题由于您使用的XCode另一件事可能会引起麻烦。看起来XCode在换行之前不会刷新缓冲区;冲洗不起作用。我们最近有几个问题(例如C++ not showing cout in Xcode console but runs perfectly in Terminal)。这似乎是XCode版本中的一个错误。
尝试通过我所描述的刷新你的缓冲区,并尝试使用终端进行编译。如果它工作在那里你的代码是好的,这是一个XCode问题。
是数学相关的问题还是与cout对象? –
'endl'是一个换行符和一个flush,所以你现在看到的似乎是合理的。 – user4581301