中国大学MOOC-陈越、何钦铭-数据结构-起步能力自测题
文章目录
前言
打算参加最新的一次MOOC上的数据结构课程,所以趁正式开课前把能力测试题给做了。做都做了想着就写一下总结吧,有任何问题都可以留言讨论~一、自测-1 打印沙漏 (20 分)
这道题没什么难度主要是要注意下细节。先计算出实际打印出字符的个数,这里在实现上有两种思路:
- 先用循环直接计算出可以打印出的符号个数
- 计算出沙漏的行数
以金字塔型计算,第n行中字符的个数为: 2 ∗ n − 1 2*n-1 2∗n−1,所以根据等差数列求和得一个金字塔所需总的字符数为 n 2 n^2 n2,那么沙漏的字符数为 2 ∗ n 2 − 1 2*n^2-1 2∗n2−1。
以第一种思路为例:
#include <iostream>
using namespace std;
int main()
{
int num =0;
char character ='\0';
cin>>num>>character;
int numblank =0; //空格数
int tempnum =num-1;
int temp =tempnum;
int i = 1;
for(i =1;true;i++)
{
tempnum=tempnum - (i*2+1)*2;
if(tempnum<0)
{
break;
}
temp = tempnum;
}
i--;
for(int index =i;index>0;index--)
{
int h = index *2+1;
int blanktemp =numblank;
while(blanktemp--)
cout<<' ';
while(h--)
{
cout<<character;
}
cout<<endl;
numblank ++;
}
int blanktemp =numblank;
while(blanktemp--)
cout<<' ';
cout<<character<<endl;
for(int index