【寄语】
人们生活中会遇到许多路口,做出若干选择。我们又该如何让机器做出合适的选择呢?
【知识准备】
|
|
否 |
条件成立吗? |
是 |
语句1 |
语句2 |
条件成立吗? |
否 |
是 |
语句 |
【自主学习】判断数正负
(二中openjudge/ 编程入门之逻辑表达式与条件分支 No.1 )
程序1
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
if(n==0) cout<<"zero"<<endl;
if(n>0) cout<<"positive"<<endl;
if(n<0) cout<<"negative"<<endl;
return 0;
}
程序2
#include<iostream>
using namespace std;
int main()
{
long n;
cin>>n;
if (n>0) cout<<"positive"<<endl;
else if (n==0) cout<<"zero"<<endl;
else cout<<"negative"<<endl;
return 0;
}
附:关系表达式表
等于 | 不等于 | 大于 | 小于 | 大于等于 | 小于等于 |
== | != | > | < | >= | <= |
优先级别:低 | 优先级别:高 |
【任务】课堂练习1:奇偶数判断
(二中openjudge/ 编程入门之逻辑表达式与条件分支 No.3 )
程序
#include <iostream>
using namespace std;
int main()
{
int a;
;
if ( ) cout<< ;
else cout<< ;
return 0;
}
【探究学习】逻辑运算符
逻辑或 | 逻辑与 | 逻辑非 |
|| | && | ! |
优先等级:低 | 优先等级:中 | 优先等级:高 |
逻辑非
a | !a | |
值 | 0 | 1 |
1 | 0 |
逻辑与
a | b | a&&b | |
值 | 0 | 0 | 0 |
0 | 1 | 0 | |
1 | 0 | 0 | |
1 | 1 | 1 |
逻辑或
a | b | a||b | |
值 | 0 | 0 | 0 |
0 | 1 | 1 | |
1 | 0 | 1 | |
1 | 1 | 1 |
提示:
当if和else后面有多个要操作的语句时,要用“{}”括起来。几个语句括起来的语句组合称为复合语句。
【自主学习】分段函数
(二中openjudge/ 编程入门之逻辑表达式与条件分支 No.3 )
程序一
#include <stdio.h>
using namespace std;
int main()
{
float x,y;
scanf("%f",&x);
if (x>=0 && x<5)
{
y=-x+2.5;
printf("%.3f",y);
}
if(x>=5 && x<10)
{
y=2-1.5*(x-3)*(x-3);
printf("%.3f",y);
}
if(x>=10 && x<20)
{
y=x/2.0-1.5;
printf("%.3f",y);
}
return 0;
}
程序二
#include <iostream>
#include < >
using namespace std;
int main()
{
float x,y;
cin>>x;
if (x>=0 && x<5)
{
y=-x+2.5;
cout<<fixed<<setprecision(3)<<y;
}
if(x>=5 && x<10)
{
y=2-1.5*(x-3)*(x-3);
cout<<fixed<<setprecision(3)<<y;
}
if(x>=10 && x<20)
{
y=x/2.0-1.5;
cout<<fixed<<setprecision(3)<<y;
}
return 0;
}
【任务】课堂练习2:判断闰年
(二中openjudge/ 编程入门之逻辑表达式与条件分支 No.13 )
程序
#include<iostream>
using namespace std;
int main()
{
int x;
cin>>x;
if ( )
cout<<"Y"<<endl;
else
cout<< <<endl;
return 0;
}
思考:如果判断分支有多个,譬如几月有几天,该怎么处理?
【任务】课后练习
二中openjudge/ 编程入门之逻辑表达式与条件分支 No.12、No.14。