5.循环和计数

在上里一个例子中我们输出了:

     

 

这种方法有一个主要的缺点:输出的每一行都有一个与之对应的变量。因此,即使对输出格式进行简单的更改,例如删除问候语和框架之间的空格,也需要重写程序。我们希望产生更灵活的输出形式,而不必将每行存储在局部变量中。

我们将通过单独输出每个字符来解决这个问题。

思路:

把输出当成一个二维矩阵。当第2行2列时候,输出问候语句。其他时候,如果是矩阵边缘,输出"*",其他地方输出" "。

string::size_type 仅仅是一个unsigned类型,本例中就是用来计数,统计列数。

#include <iostream>
#include <string>

using namespace std;


int main()
{
    
    int rows;
    string::size_type cols;

    int pad = 1;
    string name;
    cout << "What's your name: ";
    cin >> name;
    string greeting;
    greeting = "Hello, " + name + "!";
    rows = pad*2+3;
    cols = greeting.size()+pad*2+2;
    for(int i=0; i<rows; i++)
    {
        string::size_type c = 0;
        while(c != cols)
        {
            if(i == 2 && c == 2)
            {
                cout << greeting;
                c += greeting.size();
            }
            else
            {
                if(i == 0 || i == 4 || c == 0 || c == cols - 1)
                    cout << "*";
                else
                    cout << " ";
                c++;
            }
            
        }
        cout << endl;
    }
      

    system("pause");
    return 0;
}

 

课后习题:

1)用"*"输出一个三角形。

#include <iostream>
#include <string>

using namespace std;


int main()
{
    
    int rows = 5;
    int cols = 9;
    int mid = cols / 2;
    int count = 0;
    for(int i = 0; i < 5; i++)
    {
        int c = 0;
        while(c != cols)
        {
            if(c == mid - count || c == mid + count || i == 4)
                cout << "*";
            else
                cout << " ";
            c++;
        }
        count++;
        cout << endl;
    }
      

    system("pause");
    return 0;
}

 

转载于:https://www.cnblogs.com/billxyd/p/7028455.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值