习题6.4 逻辑或运算符OR ||
#include<iostream>
int main()
{
using namespace std;
cout << "阿稳是个帅哥吗?"; char ch; cin >> ch;
if (ch == 'y' || ch == 'Y')
cout << "你说得对,阿稳是个帅哥!";
else if (ch == 'n' || ch == 'N')
cout << "你说的不对,阿稳应该是个大帅哥!";
else
cout << "你说得很对!";
return 0;
}
习题6.5 逻辑与运算符AND &&
由于两种不同原因而结束的while循环,一个while循环将值读入到数组,一个测试(i<ArSize)在数组被填满时循环结束,另一个测试(temp >= 0)让用户通过输入一个负值来提前结束循环。
#include<iostream>
const int Arsize = 6;
int main()
{
using namespace std;
float naaq[Arsize];
cout << "Enter the NAAQs:\n";
int i = 0;
float temp;
cout << "First value: ";
cin >> temp;
while (i < Arsize && temp >= 0)
{
naaq[i] = temp;
++i;
if (i < Arsize)
{ cout << "Next value: ";
cin >> temp;
}
}
if (i == 0)
cout << "No date -- bye\n";
else
{ cout << "Enter your NAAQ: ";
float you;
cin >> you;
int count = 0;
for (int j = 0; j < i; j++)
{ if (naaq[j] > you)
++count;
}
cout << count;
}
return 0;
}
课后习题
课堂巧思
设计一个有限单个密码锁,密码为提前设定好的单个字符,用户可以输入字符,如果输错密码,提示密码错误,还有几次机会;密码错误三次则提示“no more chances”然后退出,密码正确提示”welcome”然后退出。
桂桂答题
#include<iostream>
const char code = 'c';
int main()
{
using namespace std;
char ch;
int chances = 3;
cout << "Pls enter your code.\n";
cin >> ch;
while (ch != code)
{
chances = chances - 1;
if (chances == 0)
{
cout << "Wrong, there is no chance left. Bye!\n";
return 0;
}
else
{
cout << "Wrong, there is/are " << chances << " chances left for you!\n";
cin >> ch;
}
}
cout << "welcome!\n";
return 0;
}
课后延伸
设计一个三位密码锁,密码为提前设定好的字符串,用户可以输入字符,如果输错密码,提示密码错误,输对密码则提示:”welcome“。
桂桂答题
#include<iostream>
const char code[4] = "wsg";
int main()
{
using namespace std;
char ch[4];
int i = 0;
cin >> ch[i];
while (i < 2)
{
if (ch[i] != code[i])
{
cout << "wrong\n";
break;
}
else
i++;
cin >> ch[i];
}
if (ch[i] == code[i])
cout << "welcome\n";
else
cout << "Bye\n";
}
试着这样做:如果输错任意一位密码,立马提示密码错误退出
100分
课后习题答案
课堂巧思
int count = 0;
char ch;
cout << "pls guess the code:";
while (count != 3)
{
cin >> ch;
if (ch == Code)
{
cout << "welcome\n";
return 0;
}
else
{
count++;
cout << "code wrong! " << 3 - count << " chances left\n";
}
}
cout << "no more chances";
//答案2
#include<iostream>
int main()
{
using namespace std;
const char code = 'g';
int chances = 3;
char ch;
cout << "pls enter the code:";
cin >> ch;
while (ch != code && chances != 0)
{
chances--;
cout << "wrong! " << chances << "chances left!\n";
cin >> ch;
}
if (chances == 0)
cout << "no chances left!\n";
else
cout << "welcome";
}
课后延伸
using namespace std;
const char code[4] = "wsg";
char guess[4];
int i = 0;
int count = 0;
cout << "pls enter the code: ";
cin >> guess[i];
while (i < 2 && guess[i]==code[i])
{
i++;
cin >> guess[i];
}
if (i != 2 || guess[i] != code[i])
{
cout << "wrong!";
}
else
cout << "welcome!";
return 0;