【问题标题】:Right angle triangle star pattern in C++ using while loopsC++中使用while循环的直角三角形星形图案
【发布时间】:2022-01-03 23:26:01
【问题描述】:

我想要一个模式,其中第一行的 n=4 有 4 颗星,第二行有 1 个空格和 3 颗星,第三行有 2 个空格和 2 颗星,依此类推。

****
 ***
  **
   *

代码,我试图解决这个问题。

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << endl;

    int i = 1;
    while (i <= n)
    {
        //Printing Spaces

        int space = i - 1;
        while (space)
        {
            cout << " ";
            space++;
        }

        //Printing Stars

        int j = 1;
        while (j <= n)
        {
            cout << "*";
            j++;
        }
        cout << endl;
        i++;
    }

    return 0;
}

【问题讨论】:

  • int space = i - 1; while (space) { cout &lt;&lt; " "; space++; } 如果空格以正数开头,然后在循环内的空格上加 1,那么while (space) 什么时候会是假的? (特别是因为滚动有符号整数是未定义的行为:stackoverflow.com/questions/16188263/…

标签: c++ loops while-loop


【解决方案1】:

在您的 while (space) 循环中,您不会将 space 与任何内容进行比较,因此它假定表达式始终为真。

这是一种简化的方法:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << endl;

    int i = 1;
    while (i <= n)
    {
        // print i-1 spaces
        for (int j = i-1; j >= 1; j--)
        {
            cout << " ";
        }
        // print n-i+1 stars
        for (int j = n; j >= i; j--){
            cout << "*";
        }
        cout << endl;
        i++;
    }

    return 0;
}

【讨论】:

  • 我不同意第一句话。写while (space)相当于写while ( space != 0 )
【解决方案2】:
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << endl;

    int i = 1;
    while (i <= n)
    {

        int space = i - 1;  
        while (space>=1)  // change 1.1
        {
            cout << " ";
            space--;      // change 1.2
        }

        int j = i;        // change2
        while (j <= n)
        {
            cout << "*";
            j++;
        }
        cout << endl;
        i++;
    }

    return 0;
}

我只对您的代码进行了 2 处更改,因此它可以正常工作。 第一个

而(空格>=1)

您正在做的是尝试在输出中添加空格,因此您在while() 循环中添加了space 变量,但这不会起作用,因为您必须首先决定必须根据该打印多少空格你必须把条件放在while() 循环中。为了实现这一点,添加了space--;

例如。第 4 行 i=4; 需要 3 个空格,所以 space=3; while(space&gt;=1); space--; 所以 while 循环运行 3 次并打印 3 个间隙/空格。

第二个

int j = i;

而 (j

如果您输入j=1;,那么您的间隙打印正确,但所有星星打印 4 次,因为循环总是运行 4 次。由于i=1; 的这种情况,但如果你让j=i; 第一行循环运行 4 次,第二行循环运行 3 次,.....

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2021-12-19
    • 1970-01-01
    • 2016-07-17
    • 2022-08-21
    相关资源
    最近更新 更多