编程实现以下图案: * * * * * * * * * * * * * * * * * * * *(1) 用字符数组方法。(2) 用string方法。用C++语言写
时间: 2024-12-04 09:12:03 浏览: 10
(1) 使用字符数组方法在C++中实现这个五角星图案:
```cpp
#include <iostream>
using namespace std;
void printPattern(char pattern[], int size) {
for (int i = 0; i <= size; i++) {
for (int j = 0; j < size - i; j++)
cout << " ";
for (int k = 0; k < 2 * i + 1; k++)
cout << "*";
cout << endl;
}
}
int main() {
char starPattern[5] = {'*', '*', '*', '*', '*'};
int size = sizeof(starPattern) / sizeof(starPattern[0]) - 1;
printPattern(starPattern, size);
return 0;
}
```
(2) 使用字符串方法:
```cpp
#include <iostream>
#include <string>
void printPattern(string pattern, int repetitions) {
for (int i = 0; i < repetitions; i++) {
for (int j = 0; j < repetitions - i; j++)
cout << " ";
for (int k = 0; k < 2 * i + 1; k++)
cout << "*";
cout << endl;
}
}
int main() {
string star = "*";
int repetitions = 5;
printPattern(star, repetitions);
return 0;
}
```
这两个例子都会打印出你描述的五角星图案。
阅读全文