如何使用C++打印此图案

How to print this pattern using C++?

本文关键字:打印 何使用 C++      更新时间:2023-10-16

如何打印

*000
**00
***0
****

在这里,我们必须将行数作为用户的输入,然后打印图案。我能够打印 *,但无法打印 0 和它们一起<</p>

div class="answers>
cout << "*000" << endl << "**00" << endl << "***0" << endl << "****" << endl;

因为啤酒很少 我会开始用同样愚蠢的答案回答愚蠢的问题。 :D祝技术面试好运。

这类问题通常旨在测试有效使用循环的技能。

使用这个:

    #include<iostream>
    using namespace std;
    int main()
    {
        int length; //no of lines
        cout<<"Enter the number of lines"<<endl;
        cin>>length;
        cout<<endl;
        for( int i = 0; i < length; i++)
        {
             for( int j=0;j<=i;j++ )
             {
                  cout<<"*";
             }
             for( int k=length-1; k>i;k-- )
             {
                  cout<<"0";
             }
             cout<<endl;
        }
        return 0;
    }
更改

长度值以更改行数

我猜你正在寻找类似的东西:

int lines = 4;   // lines you want to print
for (int i=1; i<=lines; i++)
{
    for (int j=0; j<i; j++)
        cout << "*";
    for (int j=0; j<lines-i; j++)
        cout << "0";
    cout << endl;
}
使用

printf 比使用 cout 更容易。使用这个:

for(int i = 1; i <= 4; ++i) {
    printf("%.*s%.*sn", i, "****", 4 - i, "0000");
}

printf 允许将宽度和精度字段指定为参数列表的一部分,这与 cout 不同,COUT 是内联硬编码的。有了这个提示,我将留给您弄清楚其余的。如有任何问题,请在下面发表评论。:)

坚持使用 0 索引和明确定义的不变量怎么样?

#include <iostream>
using namespace std;
int main()
{
  int lines = 5;
  // we have written i rows thus far
  // write [i, lines) rows
  for (int i = 0; i < lines; ++i)
  {
    // we have written j stars thus far
    // write [j, i + 1) stars
    for (int j = 0; j < i + 1; ++j)
    {
      cout << "*";
    }
    // we have written k zeros thus far
    // write [k, lines - 1 - i) zeros
    for (int k = 0; k < lines - 1 - i; ++k)
    {
      cout << "0";
    }
    cout << endl;
  }
  return 0;
}