【问题标题】:my c++ codes in xcode stopped working properly我在 xcode 中的 c++ 代码停止正常工作
【发布时间】:2017-04-12 15:16:46
【问题描述】:

我有这个代码:

#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 才会首先出现。这只是最近才开始发生的。有没有办法解决这个问题以显示正确的输出?

【问题讨论】:

  • 问题数学是否与 cout 对象有关?
  • endl 是一个换行符和一个刷新,所以你现在看到的似乎是合理的。

标签: c++ xcode


【解决方案1】:

std::cout 使用缓冲输出,应始终刷新。您可以使用std::cout.flush()std::cout &lt;&lt; std::flush 来实现此目的。

您也可以使用std::cout &lt;&lt; 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 问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多