在单独的行上循环时;需要在同一条线上

While loop looping on Separate Lines; Need to be on the Same Line

本文关键字:一条 单独 循环      更新时间:2023-10-16

>我需要我的代码在同一行上一个接一个地输出"栅栏柱",但它们在不同的行上。这是我到目前为止的代码:

#include <iostream>
using namespace std;
int main(void) {  
    int posts;
    cout << "nI can make a fence with from 2 to 18 posts.n";
    cout << "How many posts would you like to have in your fence? ";
    cin >> posts ; 
    if ((posts > 1) && (posts < 19)) {
        while ((posts > 1) && (posts < 19)) {
            cout << "|---" ; 
            posts = posts - 1;
            cout << "|n" ; 
        }
    }
    else {
        cout << "nnSorry, no can do.n";
    }
 }

这就是它输出的内容:

I can make a fence with from 2 to 18 posts.
How many posts would you like to have in your fence? 4   
|---|  
|---|  
|---|   

将 cout <<"|" 移到 while 循环之外。

while ((posts > 1) && (posts < 19)) 
{
    cout << "|---" ; 
    (posts = posts - 1) ;
}
cout << "|n" ; 
}

内部循环替换为:

while (--posts)
    cout << "|---";
cout << "|n";