计算机考研机试指南(四)

编程日记 cha2-04 排版题
输出梯形(oj无)
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <iomanip>
using namespace std;
/*
    题目:输出梯形
    用时:tomato *
    思路:输出时设置宽度setw默认为左对齐,只能人工添加空格


*/

int main()
{
    int h;
    while (cin>>h)
    {
        int width = h + 2*(h-1);
        for (int i=0;i<h;i++)
        {
        // cout<<setw(width)<<" "; // ★头4文件 iomanip
            for (int j = 1;j<=2*(h-i-1);j++)
                cout<<' ';
            for (int j = 1;j<=(h+2*i);j++)
                cout<<'*';
            cout<<endl;
        }
    }



    return 0;
}

叠筐
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <iomanip>
using namespace std;
/*
    题目:叠筐
    用时:tomato *
    思路:先排版再输出,n*n的二维数组,由内向外扩张圈
    填充完之后填充四个角,最后打印输出矩阵


*/

int main()
{
   int n;
   char center,out;
   char buffer[80][80];
   int i,j,k;
   char nc;
   bool flag = true;
   while (scanf("%d %c %c",&n,&center,&out)!=EOF)
   {
       // 因为格式问题:第一个筐不输出空行,非第一个筐输出空行再输出筐
       if (flag)
       {
            flag = false;
       }
       else 
        cout<<endl;
       for (i=0,j=0;i<(n+1)/2;i++,j++)
       {
           if (((n+1)/2)%2 == 0 )
                nc = i%2==0?out: center;
            else
                nc = i%2==0?center:out;

           //选择当前圈字符,现在的问题便转化为如何塑造一个空心的筐,循环缩小
           int width = n-2*i;//筐的宽度、高度:循环次数,起点为(i,j)

           for (k = 0 ; k < width ; k++)
            {
                buffer[i][j+k] = nc; // 筐上
                buffer[n-1-i][j+k] = nc; // 下
                buffer[i+k][j] = nc; // 左
                buffer[i+k][n-1-j] = nc; // 右
            }

       }
       if (n!=1)  //当N=1时没有角可以去!★★★ 如果不判断会导致不能所有用例都通过测试
       {
                  // 去掉四个角
            buffer[0][0] = ' ';
            buffer[0][n-1]=' ';
            buffer[n-1][0]=' ';
            buffer[n-1][n-1]=' ';
       }

       for (i=0;i<n;i++)
       {
           for (j=0;j<n;j++)
           {
               cout<<buffer[i][j];
           }
           cout<<endl;
       }
   }



    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值