如何打印倒三角形?

时间:2015-07-05 09:33:47

标签: c++ loops

这些天我正在学习c ++编程,因此我给自己写了一本书来学习它。我已经完成了Flow控制章节,它描述了if else循环的使用等。 我坚持这个特殊的问题: -

Write a Program To print the following :-

@@@@@@@
 @@@@@
  @@@
   @

如何使用c ++中的循环和if else语句来完成此任务。

我发现在每一行中都有两个更少的空间和一个空格。

我还为重复的@'编程,但我无法插入空格。这是我的@&#39的计划: -

#include <iostream>

using namespace std;

int main() {
    int i,j,k;
    for (i = 7; i > 0; i = i - 2) {

        for (j = 1; j <= i; ++j) {

            cout << "@" << " ";
        }
        cout << endl;
    }
    return 0;
}

3 个答案:

答案 0 :(得分:1)

我的方法

#include <iostream>
static const int FIRST_ROW = 15;

int main()
{
    for (int i = FIRST_ROW; i > 0; i -= 2)
    {
        for (int j = 0; j < (FIRST_ROW - i) / 2; ++j)
            std::cout << " ";
        for (int j = 0; j < i; ++j)
            std::cout << "@";
        std::cout << std::endl;
    }
}

答案 1 :(得分:1)

你可以在开始和第一个循环(第二个循环之前)中插入一个没有任何内容的字符串变量:(作为字符串变量g)

cout << g; 

在第二个周期之后, 第一个

g+=" ";  

你会得到你的三角形。 :)

这里是代码:

#include <iostream>

using namespace std;

int main()
{
    string g="";
    for(int i=7; i>0; i-=2)
    {
        cout << g;
        for(int j=1; j<=i; j++)
        {
            cout << "@";
        }
        cout << endl;
        g+=" ";
    }
    cout << "Press a button to exit..." << endl;
    cin.get();
    return 0;
}

希望你能理解我的英语。 :)

答案 2 :(得分:1)

只是一个不同方法的例子:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string spaces = string();
    string chars = string(7, '@');
    while (chars.size() > 0) {
        cout << spaces << chars << endl;
        spaces += ' ';
        chars.erase(max(chars.size(), 2u) - 2);
    }
    return 0;
}
相关问题