c++ - C++ 中有没有办法让循环的输出显示在同一行上?

标签 c++ loops format output

我正在我的大学学习 C++ 入门类(class)。我们被分配了一个项目来创建一个程序来使用 pi=summation ((-1)^i+1)*(4/2i-1) 的级数来近似 pi。

我需要我的输出看起来像这样:

此程序使用 n 项级数展开来近似 pi。
输入n的值> 6
pi[6] = 4[1-1/3+1/5-1/7+1/9-1/11] = 2.9760461760417560644

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
int numOfTerms;
cout <<"This program calculates pi using an n-term series expansion."<<endl;
cout <<"Enter the value for n>";
cin >>numOfTerms;

if (numOfTerms<=0)
    cout <<numOfTerms<<"is an invalid number of terms."<<endl;
else
{
    cout <<"pi["<<numOfTerms<<"] = ";
    int i;
    for (i=1; i<=numOfTerms; i++)
    {   
        double pi, sum, firstTerm, secondTerm;
        firstTerm=pow(-1,(i+1));
        secondTerm=1/(2*i-1);
        pi=firstTerm*secondTerm;
        {
            if (pi <= 4)
                cout <<firstTerm<<"/"<<secondTerm;
            else
                cout <<"You have a C++ math error.";
        }
        sum=sum+(4*pi);
        cout <<" = "<<sum<<endl;
    }   
}
return 0;
}   

我有一个早期版本的代码可以正确地对 n 系列近似求和,但它不显示等于总和的扩展系列。

我目前的版本不显示校正总和,但它在屏幕上显示 n 次 pi[n] n 行。

我愿意尝试自己计算项目的大部分内容,我只需要知道是否有办法让我的循环输出显示在一行上而不是每次迭代显示在自己的行上。

最佳答案

不要使用 endl你的工作就完成了。

endl

Inserts a new-line character and flushes the stream.

Its behavior is equivalent to calling os.put('\n') (or os.put(os.widen('\n')) for other character types), and then os.flush().

关于c++ - C++ 中有没有办法让循环的输出显示在同一行上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19189187/

相关文章:

loops - Smalltalk - 每 2 秒打印一些内容

xml - XSL 格式和计算

delphi - 在 SQLite 数据库(Delphi)中存储日期时间值的最佳方式

c++ - 如何为 QT-Designer 中的小部件设置默认可见性值?

c++ - 使用 OCL 进行人脸检测 (OPENCV)

javascript - 循环遍历单元格范围寻找值

java - 如何将一位数整数变成两位数

C++计算数组中正数/负数的数量

c++ - VC++ 允许的函数中局部变量的最大数量是多少?

linux - 在创建文件时执行 bash 脚本