Zybooks 4.18实验:C++输出步长为5的范围时换行错误求助
解决C++输出同一行的问题
你的核心问题是每次循环都调用了endl,这个操作会强制输出流换行并刷新缓冲区,所以每个整数都会单独占一行。
修改方案很简单:把换行操作从循环内部移到循环结束后,循环里只输出整数和空格:
#include <iostream> using namespace std; int main() { int x,y; cin >> x >> y; if(y>=x){ for(int i=x;i<=y;i=i+5){ // 只输出数字和空格,不换行 cout << i << " "; } // 所有数字输出完成后再换行 cout << endl; }else{ cout<< "Second integer can't be less than the first."<< endl; } return 0; }
如果担心最后会多一个末尾空格(比如输出1 6 11 这样的格式),可以稍微调整逻辑,先输出第一个数,之后的数先输出空格再输出数字:
#include <iostream> using namespace std; int main() { int x,y; cin >> x >> y; if(y>=x){ // 先输出第一个数 cout << x; // 从x+5开始循环,每次先输出空格再输出数字 for(int i=x+5;i<=y;i=i+5){ cout << " " << i; } // 最后换行 cout << endl; }else{ cout<< "Second integer can't be less than the first."<< endl; } return 0; }
两种写法都能满足“所有整数在同一行,最后再换行”的需求,第一种更简洁,第二种避免了末尾多余空格,你可以根据实验要求选择。
内容的提问来源于stack exchange,提问作者JMan
相关产品推荐
相关产品推荐

