使用 C++ 打印空心金字塔和菱形图案的程序
在此,我们将介绍如何使用 C++ 生成空心金字塔和菱形图案。我们可以非常轻松地生成实心金字塔图案。想要使其变为空心,我们需要添加一些技巧。
空心金字塔
金字塔的第一行会打印一颗星星,最后一行将打印 n 颗星星。其他行的开头和结尾只会打印两颗星,这两颗星之间会留有一些空格。
示例代码
#include <iostream>
using namespace std;
int main() {
int n, i, j;
cout << "Enter number of lines: ";
cin >> n;
for(i = 1; i<=n; i++) {
for(j = 1; j<=(n-i); j++) { //print the blank spaces before star
cout << " ";
}
if(i == 1 || i == n) { //for the first and last line, print the stars continuously
for(j = 1; j<=i; j++) {
cout << "* ";
}
}else{
cout << "*"; //in each line star at start and end position
for(j = 1; j<=2*i-3; j++) { //print space to make hollow
cout << " ";
}
cout << "*";
}
cout << endl;
}
}输出

空心菱形
菱形的第一行和最后一行会打印一颗星星。其他行的开头和结尾只会打印两颗星,这两颗星之间会留有一些空格。菱形有两部分。上半部分和下半部分。上半部分我们需要增加空格计数,下半部分我们需要减少空格计数。此处可以使用称为 mid 的另一个变量将行号分成两部分。
示例代码
#include <iostream>
using namespace std;
int main() {
int n, i, j, mid;
cout << "Enter number of lines: ";
cin >> n;
if(n %2 == 1) { //when n is odd, increase it by 1 to make it even
n++;
}
mid = (n/2);
for(i = 1; i<= mid; i++) {
for(j = 1; j<=(mid-i); j++) { //print the blank spaces before star
cout << " ";
}
if(i == 1) {
cout << "*";
}else{
cout << "*"; //in each line star at start and end position
for(j = 1; j<=2*i-3; j++) { //print space to make hollow
cout << " ";
}
cout << "*";
}
cout << endl;
}
for(i = mid+1; i<n; i++) {
for(j = 1; j<=i-mid; j++) { //print the blank spaces before star
cout << " ";
}
if(i == n-1) {
cout << "*";
}else{
cout << "*"; //in each line star at start and end position
for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow
cout << " ";
}
cout << "*";
}
cout << endl;
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP