【问题标题】:how to print a right angle triangle in c++ using single loop如何使用单循环在 C++ 中打印直角三角形
【发布时间】:2021-12-19 23:54:38
【问题描述】:

这是我为使用 single 打印模式而编写的代码,但是它不起作用,你能帮帮我吗。


    #include<iostream>
    using namespace std;
    int main()
    {
        int line, star = 0, n;
        cin >> n;
        for (line = 1; line <= n; line++)
        {
            if (star < n)
            {
                cout << "*";
                star++;
                continue;
            }
            if (star == line)
            {
                cout << endl;
                star 
            }
        }
        
        system("pause");
        return 0;
    }

【问题讨论】:

  • 打印一行 10 颗星:- std::cout

标签: c++ algorithm loops


【解决方案1】:

要打印直角三角形,我们可以使用字符串,然后在其中添加一些部分以增加字符串的长度,看起来类似于三角形。

这是我的代码:

void solve()
{  
   string a = "*";
   string add_to_a= "*";
   int n;
   cin>>n;
   for (int i = 0; i < n; ++i)
   {
       cout<<a<<"\n";
       a+=add_to_a;
   }
} 

【讨论】:

  • 如果我们必须反转直角三角形,那么串联将不起作用,因为您必须在循环中递减?
【解决方案2】:

//试试这段代码在c++中打印直角三角形

#include<bits/stdc++.h>

using namespace std;

void printPattern(int n)
{

    // Variable initialization

    int line_no = 1; // Line count
 

    // Loop to print desired pattern

    int curr_star = 0;

    for (int line_no = 1; line_no <= n; )

    {

        // If current star count is less than

        // current line number

        if (curr_star < line_no)

        {

           cout << "* ";

           curr_star++;

           continue;

        }
 

        // Else time to print a new line

        if (curr_star == line_no)

        {

           cout << "\n";

           line_no++;

           curr_star = 0;

        }

    }
}
 
// Driver code

int main()
{

    printPattern(7);

    return 0;
}

//代码的输出

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *

【讨论】:

  • 不要#include&lt;bits/stdc++.h&gt;。有小孩能找到。 Details.
猜你喜欢
  • 1970-01-01
  • 2020-10-06
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多