gpt4 book ai didi

c++ - 根据用户每行输入的术语显示新行

转载 作者:行者123 更新时间:2023-11-28 07:07:00 26 4
gpt4 key购买 nike

该程序根据用户输入的第一个术语、要计算的术语数和每行术语输出 Jugglers 系列中的术语

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

//prototype
int ValidateInput (string Prompt);


int main()
{
//local variables
long long int firstTerm;
int termsToCalc;
int termsPerLine;
int count;


//tells user what program does
cout << "Program will determine the terms in a Juggler Series" << endl << endl;

//calls user function to read in the frist term
firstTerm = ValidateInput ("Enter the first term: ");
cout << endl;

//calls user function to read in the number of terms to calculate (after the first)
termsToCalc = ValidateInput ("Enter the number of terms to calculate (after the first): ");
cout << endl;

//calls user function to read in the number of terms to display per line
termsPerLine = ValidateInput ("Enter the terms to display per line: ");
cout << endl;

cout << "First " << termsToCalc << " terms of Juggler series starting with " << firstTerm << endl << endl;

count = 1;

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

//the term is even take it to the power of 1/2 and increase the count 1
if (firstTerm % 2 == 0 )
{
firstTerm = pow(firstTerm , 0.5);
cout << setw(16) << firstTerm << endl;
count++;
}
//the term is odd take it to the power of 3/2, and increase the count 1
else
{
firstTerm = pow(firstTerm, 1.5);
cout << setw(16) << firstTerm << endl;
count++;
}
}
//continue looping until the terms to calculate is no longer less than or
// equal to the count
while (count <= termsToCalc);


return 0;
}



int ValidateInput (string Prompt)
{
//local variable
int number;

//prompts user for first term, and reads in number
cout << Prompt;
cin >> number;

//user input must be positive, a while loop will check user input and
//continue to check until the term is positive.
while (number <=0)
{
cout << "Error - Enter a positive number" << endl;
cin >> number;
}

//returns number to main function
return number;

}

这是当前的打印输出 Current print out

这就是我想要的样子 but I want it to print like this

我不知道如何编辑输出语句才能正确显示


删除 endls 并将新行语句移动到末尾后,我现在得到了正确的打印输出,但有一个额外的术语

extra term

最佳答案

首先,从这些中删除 endl:

cout << setw(16) << firstTerm << endl; // ->  cout << setw(16) << firstTerm; 

也许移动这部分:

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

循环结束。于是就变成了:

 count = 0;

do {
if (firstTerm % 2 == 0 ) {
firstTerm = pow(firstTerm , 0.5);
cout << setw(16) << firstTerm;
} else {
firstTerm = pow(firstTerm, 1.5);
cout << setw(16) << firstTerm;
}

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

count++;

} while (count < termsToCalc);

关于c++ - 根据用户每行输入的术语显示新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com