gpt4 book ai didi

c++ - 在 C/C++ 中使用星号打印带边框的菱形

转载 作者:行者123 更新时间:2023-11-27 23:26:56 25 4
gpt4 key购买 nike

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

下面的代码只渲染菱形,但我需要的是一个边框。我该怎么办?

期望:

diamond with border

现实:

diamond without border

#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/C++ 中使用星号打印带边框的菱形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8598345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com