二、复习题答案
switch (ch)
{
case 'A':a_grade++;
break;
case 'B':b_grade++;
break;
case 'C':c_grade++;
break;
case 'D':d_grade++;
break;
default:f_grade++;
break;
}
int line = 0;
char ch;
while (cin.get(ch) && ch != 'Q')
{
if (ch == '\n')
line++;
}
三、编程练习答案
1.编写一个小程序,读取键盘输入,直到遇到@符号,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写(cctype)
#include<iostream>
#include<cctype>
using namespace std;
int main()
{
char ch=0;
cout << "Enter : ";
while ((ch = cin.get()) != '@')
{
if (isdigit(ch))
continue;
else if (isupper(ch))
{
cout << (char)tolower(ch);
}
else if (islower(ch))
{
cout << (char)toupper(ch);
}
else
cout << ch;
}
return 0;
}
2.编写一个程序,最多将10个donation值读入一个double数组中。程序遇到非数字输入是结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
#include<iostream>
#include<array>
using namespace std;
int main()
{
array<double, 10>dona;
unsigned int i = 0;
int y = 0;
double mean = 0;
double sum = 0;
cout << "Please enter a donation value within 10: ";
while (i < 10 && (cin >> dona[i]))
{
sum += dona[i];
i++;
}
mean = sum / i;
for (int x = 0; x < i; x++)
{
if (dona[x] > mean)
y++;
}
cout << "The mean is: " << mean << endl;
cout << "There are " << y << " donations larger than the average." << endl;
return 0;
}
3.编写一个菜单驱动程序的雏形。该程序显示一个提供四个选项的菜单——每个选项用一个字母标记。如果该用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下
Please enter one of the following choices:
c) carnivore p)pianist
t)tree g)game
f
please enter a,c,p,t,or g:q
please enter a,c,p,t,or g:t
A maple is a tree