阅读到的一些经典C/C++语言算法及代码。在此分享。
4、打印三角形和金字塔
用" * "打印半金字塔
#include <iostream>
using namespace std;
int main()
{
int rows;
int i, j;
cout << " Enter the number of rows: " << endl;
cin >> rows;
for (i = 1; i <= rows; ++i) // i行
{
for (j = 1; j <= i; ++j) // j列
{
cout << "* ";
}
cout << "\n" << endl;
}
}
用数字打印三角形
#include <iostream>
using namespace std;
int main()
{
int rows, i, j;
cout << " Enter the number of rows: " << endl;
cin >> rows;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << j << " "; // 将上一个代码中输出的"*"换为"j "即可
}
cout << "\n" << endl;
}
}
用"*"打印金字塔
//将金字塔从中线分为左右各一半
#include <iostream>
using namespace std;
int main()
{
int rows, i, space;
int j = 0;
cout << " Enter the number of rows: " << endl;
cin >> rows;
for(i = 1; i <= rows; ++i)
{
for (space = 1; space <= rows - i; ++space)
{
cout << " ";
}
while (j != 2 * i - 1)
{
cout << "* ";
++j;
}
j = 0;
cout << "\n";
}
return 0;
}
用"*"打印倒金字塔
//从上到下变位从下到上
#include <iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << " Enter the number of rows: " << endl;
cin >> rows;
for(i = rows; i >= 1; --i)
{
for (space = 0; space <= rows - i; ++space)
cout << " ";
for (j = i; j <=2 * i - 1; ++j)
cout << "* ";
for (j = 0; j < i-1; ++j)
cout << "* ";
cout << "\n";
}
return 0;
}
5月4日更新
结合上面的方法,编写出一个打印棱形的程序
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, space;
cout << "Enter rows: " << endl;
cin >> rows;
for(i = 1; i <= rows; ++i)
{
for(space = 1; space <= rows - i; ++space)
{
cout << " ";
}
for(j = 1; j <= 2 * i - 1; ++j)
{
cout << "* ";
}
cout << endl;
}
for(i = rows - 1; i >= 1; --i)
{
for(space = 1; space <= rows - i; ++space)
{
cout << " ";
}
for(j = 1; j <= 2 * i - 1; ++j)
{
cout << "* ";
}
cout << endl;
}
}
今天看到@天花板 的一篇内容可以对上述程序进行优化。代码就不贴了,上连接:21天C语言代码训练营(第二天)
网友评论