第二章

来源:互联网 发布:单机免费进销存软件 编辑:程序博客网 时间:2024/04/30 00:32

第二章(循环与计数)

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

#include<iostream>

#include<string>

using namespace std;

int main()

{

       cout<< "please enter your name: ";

       stringname ;

       cin>> name;

       conststring greeting = "hello "+ name + " !";

       constint pad = 1;

       constint rows = pad*2+3;

       conststring::size_type cols = greeting.size() + pad*2+2;

       cout<< endl;

       for(intr = 0; r != rows; ++r){

              string::size_typec = 0;

              while(c!= cols){

                     if(r== pad+1 && c == pad+1){

                            cout<< greeting;

                            c+= greeting.size();

                     }else{

                            if(r==0|| r == rows - 1 || c == 0 || c == cols -1)

                               cout << "*";

                   else

                      cout << " ";

                ++c;

                     }

              }

              cout<< endl;

       }

       return0;

}

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

知识点:

1循环不变式:在while语句中的循环不变式可以理解成 条件成立—〉执行循环体—〉条件不成立—〉自增(自减)运算—〉条件成立  如此循环往复。

2再int类型也能运行的情况下,为什么要用string::size_type 类型?

无论何时,只要我们想定义一个变量以保存特定数据结构的大小,就应该养成使用库为特殊用途而定义的类型的良好习惯。string::size_type 是无符号整数类型,用于保存任何字符串的长度——不管这个数目有多大。然而int类型的取值是有限的。

短路求值:逻辑运算符符合左结合规律,在第一个值不满足时,也就不会进行第二个的操作。

另外:size_t类型:无符号整数类型(定义在<cstddef>中),可以保存任何对象的长度。

练习:

2-1

将pad 改成等于0就行了

2-2

改变pad值

2-3

该pad定值为及时输入。

其他的略。。。

0 0
原创粉丝点击