第17课 欧耶欧耶--逻辑运算符
第17课 欧耶欧耶--逻辑运算符
例程:
试编一个程序,输入一个整数,若是3和5的公倍数,则输出“欧耶欧耶”。
流程图如下:
代码如下:
1 /* 2 例程: 3 试编一个程序,输入一个整数,若是3和5的公倍数,则输出“欧耶欧耶”。 4 */ 5 6 #include <typeinfo> //变量类型头文件,还是有问题;无法判断int 7 #include <iostream> //包含输入输出流头文件iostream 8 using namespace std; //指明程序 使用命名空间std(标准) 9 int main() 10 { 11 int n; 12 cout<<"请输入一个整数:"; 13 cin>>n; 14 if(n%3==0) 15 if(n%5==0) cout<<"欧耶欧耶"<<endl; 16 return 0; 17 }
注:
逻辑与(而且):&&
逻辑或(或者):||
逻辑非(否):!
上面代码可以改为:
1 /* 2 例程: 3 试编一个程序,输入一个整数,若是3和5的公倍数,则输出“欧耶欧耶”。 4 */ 5 6 #include <typeinfo> //变量类型头文件,还是有问题;无法判断int 7 #include <iostream> //包含输入输出流头文件iostream 8 using namespace std; //指明程序 使用命名空间std(标准) 9 int main() 10 { 11 int n; 12 cout<<"请输入一个整数:"; 13 cin>>n; 14 if(n%3==0 && n%5==0) cout<<"欧耶欧耶"<<endl; 15 return 0; 16 }
动动脑:
2、阅读程序写结果。
1 /* 2 2、阅读程序写结果。 3 */ 4 5 #include <iostream> //包含输入输出流头文件iostream 6 using namespace std; //指明程序 使用命名空间std(标准) 7 int main() 8 { 9 int n; 10 int s=0; 11 cin>>n; 12 if (n%3==0 || n%5==0) s++; 13 cin>>n; 14 if (n%3==0 && n%5==0) s++; 15 cin>>n; 16 if (!(n%5==0)) s++; 17 cout<<s; 18 return 0; 19 }
3、完善程序。
再摸拟“比尔庄园”登录,输入正确的用户名和密码,输出欢迎语句“亲爱的小朋友,欢迎你!”,否则提示“用户名或密码不正确!”
1 /* 2 3、完善程序。 3 再摸拟“比尔庄园”登录,输入正确的用户名和密码, 4 输出欢迎语句“亲爱的小朋友,欢迎你!”, 5 否则提示“用户名或密码不正确!” 6 */ 7 8 #include <iostream> //包含输入输出流头文件iostream 9 #include <string> 10 using namespace std; //指明程序 使用命名空间std(标准) 11 int main() 12 { 13 const int USER=201701; 14 const string PSW="Computer2020@sina.com"; 15 int user; 16 string psw; 17 cout<<"用户名:"; 18 cin>>user; 19 cout<<"密码:"; 20 cin>>psw; 21 if (user==USER && psw==PSW) 22 cout<<"亲爱的小朋友,欢迎你!"<<endl; 23 else 24 cout<<"用户名或密码不正确!"; 25 return 0; 26 }
小学生C++