用c++实现3个循环的平行四边形

Parallelogram with 3 loops with c++

本文关键字:平行四边形 循环 3个 c++ 实现      更新时间:2023-10-16

这是我学计算机科学的第一年,我遇到了一些问题。教员要求编写平行四边形的代码:

输入行数:13

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

强制奇数进入(如4变为5)。规则是-我不能使用炖菜-必须只使用3个循环绘制形状-加上一个循环用于强制输入(r在3到23之间)-必须使用总行数或当前行进行所有计算(不能使用前一行,也不能生成自己的数字)

int main() {
    int control = 0;
    int i = 0, j = 0, k = 0, l = 0;
    int r = 0, c = 0, crntRow = 0, crntRow2 = 0,
        cuur_8r = 0, space = 0, star = 0;
    char a = '-', b = '+';
    //cin >> r;
    r = 11;
    if (!(r % 2))
        r++;
    c = 0;
    //cout << c << r;
    for (i = 0; i < r; i++)
    {
        space = r / 2;
        star = r / 2;
        crntRow = i;
        while (crntRow > space)
        {
            space++;
            cout << a;
        }
        //cout << j;
        for (int j = 0; j < c; j++)
        {
            if (star > j)
            {
                cout << b;
            }
        }
        c++;
        cout << 'n';
    }
}

TLDR:这是我到目前为止想出的可怕的代码,我不知道如何缩小rows/2 之后的恒星数量

您的讲师所指的三个循环是:

  1. 线路上的外环
  2. 一个循环,将空格作为每行的前缀(前半部分为0个空格)
  3. 在每行上打印星形的循环(这总是非零的)

这里有一个非常精简的例子:

int i, j, k, sp, st;
int r = 11;
// 1. An outer loop over the lines
for (i = 0; i < r; i++)
{
    if(i <= r/2) {
        sp = 0;     // No spaces in the first half
        st = i + 1; // Increasing stars in the first half
    } else {
        sp = i - r / 2;   // Increasing spaces in the second half
        st = r - i; // Decreasing stars in the second half
    }
    // 2. A loop to prefix spaces to each line (0 spaces for the first half)
    for(j = 0; j < sp; j++) cout << ' ';
    // 3. A loop to print stars on each line (this is always non-zero)
    for(k = 0; k < st; k++) cout << '*';
    cout << 'n';
}

作为一项练习,你可以在两个循环中做同样的事情:

  1. 线路上的外环
  2. 每行字符上的内部循环

在这种情况下,您必须选择在内部循环的每次迭代中打印哪个字符。