【问题标题】:I need help to writing a program that prints out shape that takes number of rows from user [closed]我需要帮助来编写一个打印出从用户那里获取行数的形状的程序[关闭]
【发布时间】:2022-01-10 17:24:25
【问题描述】:

形状应如下所示:shape

例如,这个图有 10 行。并且形状应该继续这种模式。

到目前为止,这是我的代码:

#include <iostream>
using namespace std;
int main()
{
    int rows, a, b, c, d;
    cout << "Enter the number of the rows: ";
    cin >> rows;
    for (a = 1; a <= rows; a++) {
        for (b = 1; b <= a; b = a + 4) {
            cout << "   ******" << endl;
        }
        for (c = 2; c <= rows; c += 2) {
            cout << " **********" << endl;
        }
        for (d = 3; d <= rows; d += 4) {
            cout << "************" << endl;
        }
    }
    return 0;
}

我无法将其恢复正常。比如我输入值 5 时,每行重复 5 次,但我希望行数为 5。

【问题讨论】:

  • 附带说明,在一行中声明多个变量是一种不好的做法,应该避免。
  • 这个循环似乎是错误的:for (b=1; b&lt;=a; b=a+4){ b=a+4 b 只会小于或等于 a 1 次。

标签: c++ loops shapes nested-for-loop


【解决方案1】:

这里有一个解决方案:

#include <iostream>
#include <iomanip>


int main( )
{
    std::cout << "Enter the number of the rows: ";
    std::size_t rowCount { };
    std::cin >> rowCount;

    constexpr std::size_t initialAsteriskCount { 6 };
    std::size_t asteriskCount { initialAsteriskCount };
    bool isIncreasing { };
    int fieldWidth { initialAsteriskCount + 3 };

    for ( std::size_t row = 0; row < rowCount; ++row )
    {
        std::cout << std::right << std::setw( fieldWidth ) << std::setfill(' ')
                  << std::string( asteriskCount, '*' ) << '\n';

        switch ( asteriskCount )
        {
            break; case 6:
                isIncreasing = true;
                asteriskCount += 4;
                fieldWidth = 11;
            break; case 10:
                asteriskCount += ( isIncreasing ) ? 2 : -4;
                fieldWidth = ( isIncreasing ) ? 12 : 9;
            break; case 12:
                isIncreasing = false;
                asteriskCount -= 2;
                fieldWidth = 11;
        }
    }

    return 0;
}

这可能可以简化一点。但它工作正常。

另外,请注意switch 语句的语法乍一看可能有点奇怪。但这是编写switch 块的新的、更安全的方法,并得到专家的推荐。

【讨论】:

猜你喜欢
  • 2011-03-25
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 2022-07-07
  • 1970-01-01
  • 2017-06-16
相关资源
最近更新 更多