----------------------
ASP.Net+Unity开发、
.Net培训、期待与您交流! ----------------------
while和do-while
注意:循环语句可以定义的变量名与for的表达式一的相同
----------------------
ASP.Net+Unity开发、
.Net培训、期待与您交流! ----------------------
流程控制
•顺序结构:默认的流程结构。按照书写顺序执行每一条语句。
•选择结构:对给定的条件进行判断,再根据判断结果来决定执行哪一段代码。
•循环结构:在给定条件成立的情况下,反复执行某一段代码。
选择结构-if
1.1if语句第一种方法
if (表达式) {语句};
#include <stdio.h> int main(){ if(表达式1) { 语句1 } return 0; }
if后面跟表达式,当括号里面的数值非0时则认为是真,则进入该语句,执行语句
1.2if语句的第二种方法
if(表达式){}else{}
#include <stdio.h>
int main(){
if(表达式1)
{
语句1
}else
{
语句2
}
return 0;
}
表达式成立则执行语句1,否则执行语句2
1.3if语句的第三种方法
if(表达式1){语句1}else if(表达式2){语句2}.....else{语句X}
#include <stdio.h>
int main(){
if(表达式1)
{
语句1
}else if(表达式2)
{
语句2
}else if(表达式3)
{
语句3
}else{语句4}
return 0;
}
1.4if语句的使用注意
1>比较大小时,常量值放左边,变量放右边
2>注意赋值运算符,不要写成两个=
3>if语句后面不要写;
4>如果要在if后面的语句中定义新的变量,必须用大括号{}
选择结构-switch
简单使用
switch(表达式)
{
case 数值1:
break;
…
default:
break;
}
if和switch的对比
很多情况可以互换
if用得比较多,比较灵活,switch只能某个单值
循环结构while
运行原理:
1.如果一开始条件就不成立,永远不会执行循环体
2.如果条件成立,就会执行一次循环体,执行完毕,再次判断条件是否成立......
使用举例
#include <stdio.h>
int main ()
{
int count, sum, anInteger;
printf("Enter the integers and terminate with negtive number\n");
count 0;
sum = 0;
printf(“Enter number %d:”, count+1);
scanf(“%d”, &anInteger);
while (anInteger >= 0)
{
sum += anInteger;
count++;
printf(“Enter number %d:”, count+1);
scanf(“%d”, &anInteger);
}
if (count != 0)
{
printf("The average is %f\n", sum / (double) count);
}
else
{
printf("You entered no numbers\n");
}
return 0;
}
循环结构do-while
特点:一定会执行一次循环体
while和do while循环对比
举例
int number=0;
do
{
printf(“Enter a number: “);
scanf(“%d”, &number);
} while (number < 0);
while和do-while
while
int i=0;
while(i<0)
{
i++;
}
do-while
int i=0;
do{
i++;
} while(i<0);
循环结构之for循环
For简单使用
其中表达式1是初始条件,
表达式2是循环条件,
表达式3是循环因子
for(表达式1;表达式2;表达式3)
{
循环语句;
}
注意:循环语句可以定义的变量名与for的表达式一的相同
比如:
int a;
for(a=0;a<10;a++)
表示循环10次。
可以嵌套使用。
for使用注意:
1.不要随便在for()后面写分号
2.如果要在循环体中定义新的变量,必须用大括号{}包住
while循环和for循环的比较
可以互换
for循环的变量可以及时回收
break和continue
break
1.使用场合
1> switch语句:退出整个switch语句
2> 循环结构:退出整个循环语句
* while
* do while
* for
2.注意点
只对最近的循环结构有效
举例
#include <stdio.h>
int main()
{
int n, n_factorial = 1;
Printf( “Enter integer:\n ”);
Scanf (“%d”,&n);
for (int i=1;;i++)
{
n_factorial *= i;
if (i==n)
break;
}
Printf(“n=%d, n_factorial=%d\n”,nn_factorial);
return 0;
}
continue
continue:
1.使用场合
循环结构:结束当前这次的循环体,进入下一次循环体
* while
* do while
* for
2.注意点
只对最近的循环结构有效