簡體   English   中英

如何使用單循環在c ++中打印直角三角形

[英]how to print a right angle triangle in c++ using single loop

這是我為使用 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;
    }

要打印直角三角形,我們可以使用字符串,然后向其中添加一些部分以增加看起來類似於三角形的字符串的長度。

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;
   }
} 

這是我寫的代碼,這可能會有所幫助

//試試這個代碼在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;
}

//代碼輸出

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM