您的位置:首页 > 编程语言 > C语言/C++

C++输出倒三角加数字

2016-08-25 20:50 696 查看
中兴笔试题目:

#include<iostream>
using namespace std;
class Triangle {
public:
explicit Triangle(int n) :
rows(n), sum(0), count(0), temp(0) { maxNum = rows*(rows + 1); }
void TriangleOutput();
private:
int rows;  //行数
int maxNum;	//表示三角中最大的数字
int sum;  //自由变量
int count;
int temp;
};
void Triangle::TriangleOutput()
{
for (int r = 1;r <= rows;r++)//控制行
{
for (int a = 0;a < r - 1;a++)//先输出每行的”--“
cout << "--";
count = (4 * (rows - r) + 3);//用来缓存第r行的数字和“*”的总个数
temp = (count + 1 )/ 2;
for (int c = 1,left=sum+1, right = (maxNum - sum - rows + r)//每行右半三角的第一个值
;c <=count; c++)
{
if (c <= temp)	//左半三角
{
if (c % 2 == 1)
{
cout << left;
left++;
}
if (c % 2 == 0)
cout << "*";
}
if (c > temp) //右半三角
{
if (c % 2 == 1)
{
cout << right;
right++;
}
if (c % 2 == 0)
cout << "*";
}
}
sum = sum + rows - r + 1;//得到左半三角的左右边的值
cout << endl;
}
cout << endl;
}
int main()
{
int n(0);
cout << "请输入行数n:";
cin >> n;
Triangle Tr(n);
Tr.TriangleOutput();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Triangle