5. 循环控制 Repetition
2016-08-01 本文已影响27人
53df91bc24df
Loop(循环)
5.1 循环的基本结构
重复代码段要有4个部分
1 循环语句
while
for
do-while
->for 和 while在C中可以互换,所以选择两个任意效果是一样的。
->其他语言中的习惯,for用来计数器控制循环,while用来条件式控制循环。
2 条件式
3 初始化
4 改变
5.2 while statement
#include <stdio.h>
#define MAXCOUNT 4
int main()
{
int count;
float num, total, average;
printf("Only enter %d numbers\n\n", MAXCOUNT);
count = 1;
total = 0.0;
while (count <= MAXCOUNT) {
printf("Enter a number: ");
scanf("%f", &num);
total += num;
count++;
}
average = total / MAXCOUNT;
printf("The sum is %f\n", total);
printf("The average is %f\n", average);
return 0;
}
break
强制一个即时中断||立即从switch,while,for,do-while语句中退出
break;
continue
只用于while,do-while,for。
continue;
空语句
;
5.4 for statement
#include <stdio.h>
#define MAXCOUNT 4
int main()
{
int count;
float num, total, average;
printf("Only enter %d numbers\n\n", MAXCOUNT);
total = 0.0;
for (count = 0; count < MAXCOUNT; count++) {
printf("\nEnter a number:");
scanf("%f", &num);
total += num;
}
average = total / MAXCOUNT;
printf("The sum is %f\n", total);
printf("The average is %f\n", average);
return 0;
}
5.5 Loop programming Techs
1 selection within loop
#include <stdio.h>
#define MAXNUMS 5
int main()
{
int i;
float number;
float postotal = 0.0f;
float negtotal = 0.0f;
for (i = 1; i <= MAXNUMS; i++) {
printf("Enter a number (positive or negative): ");
scanf("%f", &number);
//在循环内选择
if (number > 0) {
postotal += number;
}
else
negtotal += number;
}
printf("\nThe positive total is %f", postotal);
printf("\nThe negative total is %f\n", negtotal);
return 0;
}
2 Input data Validation
#include <stdio.h>
int main()
{
int month;
printf("\nEnter a month between 1 and 12: ");
scanf("%d", &month);
while (month <1 || month >12) {
printf("Input Error");
printf("\nEnter a month between 1 and 12: ");
scanf("%d", &month);
}
printf("The month accepted is %d\n", month);
return 0;
}
5.6 嵌套循环
至少两层循环inner loop和outer loop
#include <stdio.h>
int main()
{
int i,j;
for(i = 1; i <= 5; i++){
printf("\ni is now %d\n", i);
for (j = 1; j<=4; j++) {
printf("j=%d", j);
}
}
return 0;
}
语法
1 while
while(表达式)
语句;
2 for
for(statement) {
compound statement
}
3 跟别人说的
do
statement;
while (expression)