【问题标题】:Regarding print a pattern关于打印图案
【发布时间】:2022-01-03 02:09:50
【问题描述】:

问题 如何在数字之间给出空格?当我在cout<<j 之后添加<<" " 时,模式发生了变化。有没有其他方法可以在数字之间留出空格?

代码

#include<iostream>
using namespace std;
int main(){
int i,j=1,space,star,n;
cin>>n;
i=1;

循环

while(i<=n){
space=n-i;
 while(space){
    cout<<" ";
    space--;
 }
star=i;
while(star){
cout<<j<<" ";
j++;
star--;
}
cout<<"\n";
   i++;
}
return 0;

}

输出 对于 n=4

    1
   23
  456
 78910

我想要这个输出:-

      1
    2 3
  3 4 5
7 8 9 10

【问题讨论】:

    标签: loops c++11


    【解决方案1】:

    对于预期的输出,您只需在 while(space) 循环中添加第二个空格:

        space = n - i;
        while (space) {
            std::cout << "  "; // note: two spaces
            space--;
        }
    

    或在循环前将space 乘以2

        space = 2 * (n - i);
        while (space) {
            std::cout << ' ';
            space--;
        }
    

    你也可以#include &lt;string&gt; 跳过循环:

        space = 2 * (n - i);
        std::cout << std::string(space, ' ');
    

    另一种跳过循环的方法是 #include &lt;iomanip&gt; 并使用 std::setw

    请注意,您也可以使用std::setwstd::left 来更正while (star) 循环,以使该模式最多保持n = 13

        space = 2 * (n - i) + 1;
        std::cout << std::setw(space) << "";
    
        while (star) {
            std::cout << std::setw(2) << std::left << j;
            j++;
            star--;
        }
    

    Demo

    【讨论】:

    • 为什么 cout
    • @xaviour1504 这将使它在每次打印j 后跳到新行,并且肯定会破坏模式。
    • 对不起,我想问你为什么 cout
    • @xaviour1504 一个数字 + 一个空格组成两个字符,因此您需要两个空格来缩进每行的空白部分。
    猜你喜欢
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多