带有c ++的3个循环的平行四边形

时间:2014-11-05 20:24:58

标签: c++

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

输入行数:13

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

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

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 个答案:

答案 0 :(得分:1)

教师指的三个循环是:

  1. 线上的外环
  2. 为每行添加前缀空格的循环(前半部分为0空格)
  3. 在每一行上打印星星的循环(这总是非零)
  4. 这是一个非常精简的例子:

    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. 每行中字符的内部循环
    3. 在这种情况下,您必须在内循环的每次迭代期间选择要打印的字符。