如何更整齐地排列输出?

时间:2018-07-23 04:50:09

标签: c++ fibonacci

int main()
{
    int n, t1 = 0, t2 = 1,t3 = 2, nextTerm = 0;

    cout << "Enter the number of terms: "; cin >> n;

    cout << "Fibonacci number sequence up to " << n << ":" << endl;

    for (int i = 1; i <= n+1; i++)
    {
        if (i == 1)
        {
            cout << " " << t1;
            continue;
        }
        if (i == 2)
        {
            cout << " " << t2 << " ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        cout << nextTerm << "";
        cout << endl;
    }
    cout << "Number of times iterative function is called: " << n * 3 << endl;
    return 0;
} 

输出:

Enter the number of terms: 5
Fibonacci number sequence up to 5: 
0 1 1
2  
3
5
Number of times iterative function is called: 15

我希望输出为:

Enter the number of terms: 5
Fibonacci number sequence up to 5:
0 1 1 2 3 5
Number of times iterative function is called: 15

4 个答案:

答案 0 :(得分:2)

只需将ToString行放在ToString循环之外:

PaperSize

答案 1 :(得分:2)

唯一的问题是“ nextTerm”之后的“ endl”。它将在下一行打印新号码。只需将“ endl”放在for循环之外,它将显示所需的输出。

答案 2 :(得分:0)

int main()
 {
   int n, t1 = 0, t2 = 1,t3 = 2, nextTerm = 0;

   cout << "Enter the number of terms: "; cin >> n;

   cout << "Fibonacci number sequence up to " << n << ":" << endl;

    for (int i = 1; i <= n+1; i++)
    {
        if (i == 1)
        {
            cout << " " << t1;
            continue;
        }
        if (i == 2)
        {
            cout << " " << t2 << " ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        cout << nextTerm << " ";
    }
    cout << endl;
    cout << "Number of times iterative function is called: " << n * 3 << endl;
    return 0;
}

注意cout << endl;现在已不在for块中,只能将其写入输出一次,而不必在每次迭代后写入。

还要在for循环的最后一行添加一个空格字符。

答案 3 :(得分:0)

使用endl or \n

#include <iostream>
using namespace std;

int main() {
    int n, a = 0, b = 1, c;
    cout << "Enter the number of terms: ";
    cin >> n;
    cout << "\nFibonacci number sequence up to " << n << ":"<<"\n";
    if(n >= 0) cout << a << " ";
    if(n >= 1) cout << b << " ";
    for(int i = 2; i <= n; i++){
        c = a + b;
        cout<<c<<" ";
        a = b;
        b = c;
    }
    cout << "\nNumber of times iterative function is called: " << n * 3; 
    return 0;
}