仅在向量末尾打印新行 - "if"语句在"for"循环之外



代码:

#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语句从循环中放置出来。该限制语句的范围是仅在向量"系列"末尾添加新行。我什么也没想到,但可以肯定的是我经历了足够的经验,还有另一个更优雅的解决方案。我在这里问,因为我必须提交另一个作业,而我不想提交同样的错误。

ps:另一个评论是:轻度征服。我真的发表了很多评论吗?

您在for loop末尾打印endl,因此您可以在从循环中出去并在for for for for for循环中删除endl的线路,>它将为您提供相同的结果

代码:

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;
}

您要做的是在最后一个元素之后打印一个newline。在这里,您是否正在检查每个元素,如果它是最后一个元素。但是,您无需这样做。

做"最后一个元素之后"是"在所有元素之后"的方法,因此在循环之后。只需处理所有元素与for循环,然后打印newline。

我不提供代码,因为这是一个作业,但这应该足够清楚。

关于评论:不要记录显而易见的。当然,对于不同的层次,显而易见的是不同的。但是对于"系列"向量的声明,该评论不会在代码中添加任何内容。

最新更新