iterations; std::cout > term; //End inputs std::-6ren">
gpt4 book ai didi

c++ - 仅在 vector 末尾打印新行 - "if"循环之外的 "for"语句

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:30 25 4
gpt4 key购买 nike

代码:

#include <iostream>
#include <vector>

int main () {

std::cout << "Please, enter the number of iterations: "; //Inputs

int iterations;
std::cin >> iterations;

std::cout << "Which term would you like to know: ";

int term;
std::cin >> term; //End inputs

std::vector<int> series; //definition of vector "series"

for (int n = 1; n <= iterations; n++) { //creation of "series"

int next = (2 * n - 3);
series.push_back(next);

}

std::cout << "The value of term " //prints the n term
<< term
<< " is: "
<< series[term-1] //term-1 "adjust" the indexing
<< std::endl;

std::cout << "The entire serie up to "
<< iterations
<< " terms is: ";

for (int i = 0; i < series.size(); i++) { //prints (elements of vector) "series"

std::cout << series[i] << ' ';

if (i == series.size()-1) { //new line only at the end the series

std::cout << std::endl;
}

}

return 0;

}

我得到了 9/10 的评论:“如果循环内的条件只会满足一次,但每次都会检查。移出循环”。我真的不知道如何将 if 语句置于循环之外。该 for-if 语句的范围是仅在 vector “系列”的末尾添加一个新行。我不能考虑其他任何事情,但可以肯定的是我有足够的经验并且还有另一个更优雅的解决方案。我在这里问是因为我必须提交另一份作业,我不想提交时出现同样的错误。

PS:另一条评论是:轻度过度评论。我真的评论太多了吗?

最佳答案

你在for循环的最后打印了endl,所以你可以在退出的时候加上endl这一行循环并删除 for 循环处的行,它会给你相同的结果

代码:

for (int n = 1;  n <= iterations; n++) {    //creation of "series"

int next = (2 * n - 3);
series.push_back(next);

}

std::cout << "The value of term " //prints the n term
<< term
<< " is: "
<< series[term-1] //term-1 "adjust" the indexing
<< std::endl;

std::cout << "The entire serie up to "
<< iterations
<< " terms is: ";

for (int i = 0; i < series.size(); i++) { //prints (elements of vector) "series"

std::cout << series[i] << ' ';
}
std::cout << std::endl;
return 0;

}

关于c++ - 仅在 vector 末尾打印新行 - "if"循环之外的 "for"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46367405/

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