文章目录(Table of Contents)
内容摘要
这一篇主要介绍C中的选择控制结构,包括if和switch;
- if语句 : 多重判断(else if); 逻辑表达式(&&, ||); 三目运算符(max=(a>b)?a:b)
- switch语句 : 使用switch实现简单的加减计算器;
if语句学习与说明
if语句第一段包含多重判断和逻辑表达式的写法;
if语句第二段包含三目运算符的写法;
- #include<stdio.h>
- int main(){
- /*
- if判断语句实现选择结构
- - 包含多个判断
- - 包含逻辑运算符和逻辑表达式
- */
- double number = 0;
- printf("Please enter a number!\n");
- scanf("%lf",&number);
- if((number<0)||(number>100)){
- printf("%0.2lf is less than 0 or greater than 100.\n",number);
- }
- else if(number<10){
- printf("%0.2lf is greater than 0 but is less than 10.\n",number);
- }
- else if((number>50)&&(number<100)){
- printf("%0.2lf is greater than 50 but is less than 100.\n",number);
- }
- else{
- printf("else;");
- }
- // 三目运算符 表达式1?表达式2:表达式3
- // 下面两种写法的意思相同
- int max,a,b;
- scanf("%d%d",&a,&b);
- if(a>b)
- max = a;
- else
- max = b;
- printf("The large one in %d and %d is %d.\n",a,b,max);
- // 下面的三目运算符和上面的意思相同;
- scanf("%d%d",&a,&b);
- max = (a>b)?a:b;
- printf("The large one in %d and %d is %d.\n",a,b,max);
- return 0;
- }
运行结果如下:
switch语句学习与说明
注意switch中每个case后面都有一个break;
- #include<stdio.h>
- int main(){
- /*
- switch语句实现多分支选择结构
- - 实现一个加减计算器
- - 注意switch中每个case后面都有一个break
- */
- double number1 = 0.0;
- double number2 = 0.0;
- char operation=0;
- printf("Please Enter the calculation:\n");
- scanf("%lf%c%lf",&number1,&operation,&number2);
- switch(operation){
- case '+':
- printf("%0.2lf + %0.2lf = %0.2lf\n",number1,number2,number1+number2);
- break;
- case '-':
- printf("%0.2lf - %0.2lf = %0.2lf\n",number1,number2,number1-number2);
- break;
- default:
- printf("Can't Recongize Your Operation!\n");
- }
- return 0;
- }
- 微信公众号
- 关注微信公众号
- QQ群
- 我们的QQ群号
评论