C++精讲2

来源:互联网 发布:珠海联邦制药知乎 编辑:程序博客网 时间:2024/06/10 21:34

接上一篇博客:

一.循环结构

C++中有三种循环控制语句

1.while语句

while   (表达式)  语句

执行顺序:先判断表达式(循环控制条件)的值,若表达式的值为true,在执行循环体语句。

for example:

 13 #include <iostream>
 14 using namespace std;
 15 int main()
 16 {
 17     int i=1,sum=0;
 18     while(i<=10)
 19     {
 20         sum+=i;
 21         i++;
 22     }  
 23     cout<<"sum="<<sum<<endl;
 24     return 0;         
 25 }

编译运行:

[hongfuhao@localhost ~]$ g++ 2_5.cpp  -o 2_5
[hongfuhao@localhost ~]$ ./2_5 
sum=55
2.do.....while语句

do  语句

while (表达式)

执行顺序:先执行循环体语句,后判断循环条件表达式的值,表达式为true时,继续执行循环体,表达式为false则结束循环。

for example:

输入一个整数,将各位数字反转后输出。

 13 #include <iostream>
 14 using namespace std;
 15 int main()
 16 {
 17     int n,right_digit,newnum=0;
 18     cout<<"Enter the number:";
 19     cin>>n;         
 20     cout<<"The number in reverse order is ";
 21     do 
 22     {
 23         right_digit=n%10;
 24         cout <<right_digit;
 25         n/=10;
 26     }while(n!=0);
 27     cout<<endl;
 28     return 0;
 29 }  
编译运行:

[hongfuhao@localhost ~]$ g++ 2_6.cpp 
[hongfuhao@localhost ~]$ ./a
a.out  app/   
[hongfuhao@localhost ~]$ ./a.out 
Enter the number:365
The number in reverse order is 563
[hongfuhao@localhost ~]$ ./a.out 
Enter the number:500
The number in reverse order is 005
[hongfuhao@localhost ~]$ ./a.out 
Enter the number:1005
The number in reverse order is 5001

3.for语句

使用最为灵活,既可以用于循环次数确定的情况,也可以用于循环次数未知的情况。

for (初始语句;表达式1;表达式2)

与C语言中用类似

7.循环嵌套

1.选择嵌套

2.循环嵌套

3.循环与选择相互嵌套

8.控制语句

break:跳出循环

continue:跳出本次循环

goto: 跳转到语句标号所指定的语句

8.自定义数据类型

C++不仅有丰富的内置基本数据类型,而且用户自定义数据类型。自定义数据类型有:枚举类型,结构类型,联合类型,数组类型,类类型等

8.1typedf声明

typedef 已有类型名   欣类型名表;

8.2枚举类型enum

enum  枚举类型名 {变量值列表};

//对枚举元素按常量处理,不能他们赋值;

//枚举元素具有默认值,依次为:0,1,2,3。。。。。

//也可以在声明时另行定义枚举元素的值:enum Weekend{SUU=7,MON=1,TUE=2,WED,THU,FRI,SAT};


0 0