输出所需的列数

Output desired number of columns

本文关键字:输出      更新时间:2023-10-16

我想了解一些关于如何让我的程序由用户输出所需列数的提示。例如,如果用户为termsPerLine输入2,则程序应在两列中打印Juggler系列生成的值,或者如果用户为termsPerLine、3列等输入3。输出变量为firstTerm。任何帮助都将是伟大的。

#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int ValidateInput(string Prompt);
int main()
{
    int count;
    double Odd;
    double Even;
    long long int firstTerm;
    int noOfTerms;
    int termsPerLine;
    cout << "Program will determine the terms in a Juggler Series" << endl << endl;
    firstTerm = ValidateInput("Enter the first term: ");
    noOfTerms = ValidateInput("Enter the number of terms to calculate (after first): ");
    termsPerLine = ValidateInput("Enter the terms to display per line: ");
    cout << "First " << noOfTerms << " terms of JUGGLER SERIES starting with " << firstTerm << endl;
    count = 1;
    do
    {
        if (firstTerm % 2 == 0 )
        {
            firstTerm = pow(firstTerm , 0.5);
            cout << setw(16) << firstTerm << endl;
            count++;
        }
        if (firstTerm % 2 != 0 )
        {
            firstTerm = pow(firstTerm, 1.5);
            cout << setw(16) << firstTerm << endl;
            count++;
        }
    }
    while (count <= noOfTerms);
    cout << endl;
    system("Pause");
    return 0;
}

int ValidateInput( string Prompt)
{
    int num;
    cout << Prompt << endl;
    cin >> num;
    while ( num <= 0 )
    {      
        cout << "Enter a positive number" << endl;
        cin >> num;
    } 
    return num;  
}

在循环的顶部尝试这个:

if ((count % termsPerLine) == 0)
{
    cout << "n";
}

或者这个在循环的底部:

if ((count % termsPerLine) == termsPerLine)
{
    cout << "n";
}

只需将循环修复为:

for (count = 1; count <= numOfTerm; count++)
{
if(firstTerm % 2 == 0)
    firstTerm = pow(firstTerm, 0.5);                        
else
    firstTerm = pow(firstTerm, 1.5);

if(count % termPerLine != 0)
    cout << setw(15) << firstTerm;
else
    cout << setw(15) << firstTerm <<  endl;
};