zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    关于VS2005使用VC++创建MFC智能设备应用程序,总是创建失败解决方法
    远峰E路航V700pro进入wince桌面方法与安装游戏方法
    Arduino IDE上搭建ESP8266环境
    JavaScript Tutorial
    TinyOS Term & Example
    Installation for TinyOS on Ubuntu 16.04
    MySQL Manipulation
    泰勒级数&傅立叶级数(通信层面)
    Choose a different branch in github
    初窥Makefile
  • 原文地址:https://www.cnblogs.com/billxyd/p/7028455.html
Copyright © 2011-2022 走看看