0

我想获得一些关于如何让我的程序输出用户所需数量的列的提示。例如,如果用户为 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;  
}
4

2 回答 2

1

在循环顶部试试这个:

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

或者在循环的底部:

if ((count % termsPerLine) == termsPerLine)
{
    cout << "\n";
}
于 2013-02-10T19:45:01.777 回答
0

只需将您的循环修复为:

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;

};
于 2014-02-16T04:20:31.517 回答