向此钻石代码寻求帮助

时间:2017-01-15 06:00:57

标签: c++ for-loop

有人能告诉我如何修改我的代码。

我想仅使用两个循环打印菱形图案。 如果我输入5,钻石应该是这样的:

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

我已经完成了一半。

这是我到目前为止所得到的。

  5
  *  
 *** 
*****
 ****
  ***

以下是我的代码:

#include <iostream>
using namespace std;
// print diamond. Instead of finding * pattern, just find "  " 's pattern.
int main()
{
    int size;
    cin >> size;
    int m = size / 2;

    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) { //   Before || is the left part. After || is right part
            if ((row < m && (col < m - row || col > m + row)) || (row > m && col < row - m))
                cout << " ";

            else
                cout << "*";
        }
        cout << endl;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

https://github.com/Erendile/DiamondShape/blob/main/diamondShape.c

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #define SIZE 17

    int main()
    {
        for(int i = 0, k = 0, l = SIZE / 2; i < SIZE; k++)
        {
            if(k == abs((SIZE / 2) - i))
            {
                for(int j = 0; j < 2 * abs(abs(l) - (SIZE / 2)) + 1; j++) // 2x + 1 -> 1, 3, 5, 7, 9...
                    printf("*");

                printf("\n"), i++, k = -1, l--;
                continue;
            }
            printf(" ");
        }
        return 0;
    }

答案 1 :(得分:0)

@Shawn使用我的代码进行打印。如果你想使用你的代码,只需编写单独的for循环来打印钻石的缺点。

    #include <iostream>
    using namespace std;
    int main() 
    {//code
        int n, c, k, space = 1;
        cout<<"\n\nEnter number of rows: ";
        cin>>n;
        space = n - 1;
        for (k = 1; k<=n; k++)
        {
            for (c = 1; c<=space; c++)
                cout<<" ";
            space--;
            for (c = 1; c<= 2*k-1; c++)
                cout<<"*";
            cout<<"\n";
        }
        space = 1;
        for (k = 1; k<= n - 1; k++)
        {
            for (c = 1; c<= space; c++)
                cout<<" ";
            space++;

            for (c = 1 ; c<= 2*(n-k)-1; c++)
                cout<<"*";

            cout<<"\n";
        }
        return 0;
    }