基础的 if else
习题6.1
循环输入字符,统计输入了多少个空格字符,如果输入.字符则停止统计
#include <iostream>
int main()
{
using namespace std;
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.')
{
if (ch == ' ')
++spaces;
++total;
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " character total in sentence";
return 0;
}
习题6.2
加密字符,循环输入字符,对除了换行符外的所有字符加密,加密方式为对应ASCII码+1,如果输入.字符则停止。
#include <iostream>
int main()
{
using namespace std;
char ch;
cout << "Type, and I shall repeat.\n";
cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
{
std::cout << ch;
}
else
std::cout << ++ch;
std::cin.get(ch);
}
std::cout << "\npls excuse me for the slight confusion";
return 0;
}
注意一点,++ch不能替换为ch+1,因为1为整型,若ch+1返回的值为整型数字而不再是字符。
同样的,++ch也不能替换为ch++,因为ch++在代码中的效果会是,代码先使用ch输出,再使ch++
习题6.3
猜数字游戏,给定一个数字,输入数字猜该数字,猜错了会提示高了还是低了,直到猜对为止。
#include <iostream>
const int Fave = 27;
int main()
{
using namespace std;
int n;
cout << "Enter a number in the range 1-100 to find my favorite number: ";
do
{
cin >> n;
if (n < Fave)
cout << "Too low!";
else if (n > Fave)
cout << "Too high!";
else
cout << "You are right!\n";
} while (n != Fave);
return 0;
}
课后习题
100分
改进与加强
习题6.3中使用的循环为do while,请你使用for循环和while循环分别重写习题6.3,体会一下阿稳说do while在此处的便利之处。
桂桂答题:
1.采用for循环:
#include<iostream>
const int Fave = 89;
int main()
{
using namespace std;
int n;
cout << "Enter a number in the range 1-100 to find my favorite number: ";
for (int n = 0; n != Fave;)
{
cin >> n;
if (n < Fave)
cout << "Too low!\n";
else if (n > Fave)
cout << "Too high!\n";
else
cout << Fave << " is right!\n";
}
return 0;
}
2.采用while循环:
using namespace std;
int n;
cout << "Enter a number in the range 1-100 to find my favorite number: ";
while (n != Fave)
{
cin >> n;
if (n < Fave)
cout << "Too low!\n";
else if (n > Fave)
cout << "Too high!\n";
else
cout << Fave << " is right!\n";
}
return 0;
}
总结
三个循环本质没有太多区别,do while 先做了do后面语句块内容后,再由while内部条件进行判断;for循环内部需要对变量进行初始化、条件以及判断次数;while循环只需要条件。
巩固与提高
设计一个单个密码锁,密码为提前设定好的单个字符,用户可以输入字符,如果输错密码,提示密码错误。
如果你想还可以增加循环使其反复输入密码直至正确才退出
桂桂答题:
#include<iostream>
const char ch1 = 'c';
int main()
{
using namespace std;
char ch2 = 0;
cin >> ch2;
for (; ch2 != ch1;)
{
cout << "Your code is wrong.\n";
cin >> ch2;
}
cout << "The code is right!";
return 0;
}
答案
课后习题1答案
//for循环版本
cin >> n;
if (n < Fave)
cout << "Too low!";
else if (n > Fave)
cout << "Too high!";
else
cout << "You are right!\n";
for (; n != Fave;)
{
cin >> n;
if (n < Fave)
cout << "Too low!";
else if (n > Fave)
cout << "Too high!";
else
cout << "You are right!\n";
}
//while循环版本
cin >> n;
if (n < Fave)
cout << "Too low!";
else if (n > Fave)
cout << "Too high!";
else
cout << "You are right!\n";
while (n != Fave)
{
cin >> n;
if (n < Fave)
cout << "Too low!";
else if (n > Fave)
cout << "Too high!";
else
cout << "You are right!\n";
}
课后习题2答案
char ch;
cout << "pls guess the code:";
cin >> ch;
if (ch != Code)
{
cout << "code wrong";
}
else
{
cout << "welcome!";
}