c语言_Day10_07_09
c语言_Day10_07_091、结构化语言
c语言是一门结构化的编程语言,其一共包含三种结构:
[*]顺序结构
[*]选择结构
[*]循环结构
2、分支语句
1、if语句
[*]单分支
if (表达式)
{
语句...
}
[*]双分支
if (表达式)
{
语句...
}
else
{
语句...
}
[*]多分支
if (表达式)
{
语句...
}
else if (表达式)
{
语句...
}
else
{
语句...
}int main()
{
int age;
printf("Please input a number of age: \n");
scanf("%d", &age);
if (age >= 0 && age < 200)
{
printf("Your age is %d\n", age);
}
else
{
printf("Error!!!");
}
return 0;
} 常见的错误(或引起误解)代码:
int a = 10;
if(18 <= a <= 28)
{
......
} 上述代码执行后会进入选择体,其原理为:
(18 >2、打印所有1-100的奇数
int isOdd(int num)
{
return num % 2;
}
int main()
{
int num = 2;
if (isOdd(num))
{
printf("%d is Odd\n", num);
}
else
{
printf("%d is Even\n", num);
}
for (int i = 1; i <= 100; i++)
{
if (isOdd(i))
{
printf("%d ", i);
}
if (i % 10 == 0)
{
printf("\n");
}
}
return 0;
} 2、switch语句
一种专用于实现多分支结构的分支语句
switch (整形表达式)
{
case 整形常量表达式: 语句...
}int main()
{
int day;
scanf("%d", &day);
switch (day)
{
case 1:
{
printf("Monday");
break;
}
case 2:
{
printf("Tuesday");
break;
}
case 3:
{
printf("Wednesday");
break;
}
case 4:
{
printf("Thursday");
break;
}
case 5:
{
printf("Friday");
break;
}
case 6:
{
printf("Saturday");
break;
}
case 7:
{
printf("Sunday");
break;
}
default:
{
printf("Error!!!");
break;
}
}
return 0;
} break关键字用于跳出case的代码块,但当需表达一段区间时应去除break以实现穿透
int main()
{
int day;
scanf("%d", &day);
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("工作日\n");
break;
case 6:
case 7:
printf("休息日\n");
break;
default:
printf("Error!!!");
break;
}
return 0;
} 注:case和default没有强制的顺序,若前置default代码依然正常运行
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:
m++;
case 2:
n++;
case 3:
switch (n)
{
case 1:
n++;
case 2:
m++;
n++;
break;
}
case 4:
m++;
break;
default:
break;
}
printf("n = %dm = %d\n", n, m);
return 0;
}switch语句内可嵌套if语句和switch语句
文档来源:51CTO技术博客https://blog.51cto.com/u_15285915/3032533
页:
[1]