中使用星号打印带有边框的菱形

中使用星号打印带有边框的菱形

本文介绍了在C / C ++中使用星号打印带有边框的菱形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C / C ++中使用星号打印带有边框的菱形。

I need to print out a diamond shape with a border using asterisks in C/C++

下面的代码只渲染钻石,但我需要的是一个边界。我应该怎么办?

The code below renders only the diamond, but what I need is one what a border. what should I do?

期望:

现实:

#include <iostream>

void PrintDiamond(int iSide) {
    using namespace std;
    int iSpaces = iSide;
    int iAsterisks = 1;
    // Output the top half of the diamond
    for (int iI = 0; iI < iSide; ++iI) {
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        for (int iJ = 0; iJ < iAsterisks; ++iJ) {
            cout << "*";
        }
        cout << endl;
        --iSpaces;
        iAsterisks += 2;
    }
    // Output the bottom half of the diamond
    for (int iI = 0; iI <= iSide; ++iI) {
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        for (int iJ = 0; iJ < iAsterisks; ++iJ) {
            cout << "*";
        }
        cout << endl;
        ++iSpaces;
        iAsterisks -= 2;
    }
}

int main()
{
    // Print a diamond with side = 4
    PrintDiamond(4);

    return 0;
}


推荐答案

#include <iostream>

void PrintDiamond(int iSide) {
    using namespace std;
    int iSpaces = iSide;
    int iAsterisks = 1;
    // Output the top half of the diamond

    // ADDED: here you print the top border, the number of * is
    // calculated from iSide
    for (int i = 0; i < iSide*2+3; i++)
        cout << "*";
    cout << endl;


    for (int iI = 0; iI < iSide; ++iI) {
        // ADDED: print one * of the left border, and several blanks
        cout << "*";
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }

        // here is your original code that prints the main part
        for (int iJ = 0; iJ < iAsterisks; ++iJ) {
            cout << "*";
        }

       // ADDED: the same as the left border, we print blanks and then
       // one * of the right border
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        cout << "*";
        cout << endl;

        --iSpaces;
        iAsterisks += 2;
    }
    // Output the bottom half of the diamond
    for (int iI = 0; iI <= iSide; ++iI) {
        cout << "*";
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        for (int iJ = 0; iJ < iAsterisks; ++iJ) {
            cout << "*";
        }
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        cout << "*";
        cout << endl;
        ++iSpaces;
        iAsterisks -= 2;
    }

    // ADDED: we end up with the bottom border, which is the same as the top one
    for (int i = 0; i < iSide*2+3; i++)
        cout << "*";
    cout << endl;
}

int main()
{
    // Print a diamond with side = 4
    PrintDiamond(4);

    return 0;
}

这篇关于在C / C ++中使用星号打印带有边框的菱形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 10:39