分享一下 一个关于打印三角形和菱形的程序
#include<iostream>using namespace std;
void DrawTri();
void DrawDia();
int main()
{
int type=0;
cout<<"选择你需要的图形:\n";
cout<<" 1.三角形\n";
cout<<" 2.菱形\n";
cin>>type;
while(!(cin.good()&&type==1||type==2))
{
cin.clear();
cin.ignore(1024,'\n');
cout<<"输入的图形类型不正确请重新输入:\n";
cin>>type;
}
switch(type)
{
case 1:
DrawTri();
break;
case 2:
DrawDia();
break;
default:
cout<<"输入的图形类型不正确请重新输入:\n";
break;
}
return 0;
}
void DrawTri()
{
int layer=0;
cout<<"输入层数:\n";
cin>>layer;
while(!(cin.good()&&layer>1))
{
cin.clear();
cin.ignore(1024,'\n');
cout<<"输入的层数不正确或输入的层数小于2请重新输入:\n";
cin>>layer;
}
cout<<layer<<"层三角形:\n";
for(int i=1;i<=layer;i++)
{
for(int j=1;j<=(layer-i);j++)
{
cout<<" ";
}
for(int k=1;k<=2*(i-1)+1;k++)
{
cout<<"*";
}
cout<<"\n";
}
}
void DrawDia()
{
int layer = 0;
//记录中间层
int mid;
cout<<"输入层数:\n";
cin>>layer;
while(!(cin.good() && layer > 3 && (layer%2 != 0))) {
cin.clear();
cin.ignore(1024,'\n');
cout<<"输入的层数类型不正确或层数小于3或层数不为基数,请重新输入:\n";
cin>>layer;
}
mid = (layer + 1)/2;
cout<<layer<<"层菱形:\n";
for(int i = 1; i <= layer; i++) {
int j;
for(j = 1;j <= abs(i - mid); j++) {
cout<<" ";
}
for(int k = 1; k <= (mid - j) * 2 + 1; k++) {
cout<<"*";
}
cout<<"\n";
}
}