6.2 编写一个程序,最多将10个donation值读入一个double数组中(如果你愿意,也可以使用模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
#include <iostream>
#include <array>
using namespace std;
int main()
{
int num = 0;
int index = 0;
double coverage = 0, sum = 0;
array<double, 10> arr;
cout << "请输入donation值:";
while (index < 10 && cin >> arr[index])
{
sum = sum + arr[index];
index++;
cout << "请继续输入donation值:";
}
cout << "你输入了" << index << "个数,和是:" << sum << endl;
if(index > 0)
coverage = sum / index;
cout << "平均值是:" << coverage << endl;
for (int i = 0; i < index; i++)
{
if (coverage < arr[i])
{
num++;
}
}
cout << "输入的数中有" << num << "个大于平均值" << endl;
return 0;
}
6.3编写一个菜单驱动程序的雏形。该程序显示一个提供四个选项的菜单--每个选项用一个字母表标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入有效的字母,直到用户这样选择为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:
#include <iostream>
#include <array>
using namespace std;
int main()
{
char input;
cout << "Please enter one of the following choices: " << endl;
cout << "c) carnivore p)pianist\n"
<< "t)tree g)game\n" << "f" << endl;
cout << "please enter a,c,p,t,or g: ";
for (;;)
{
cin >> input;
switch (input)
{
case 'c':
cout << "你选择的是carnivore" << endl;
cout << "重新选择的话请重新输入,不重新选择的话请按q退出" << endl;
break;
case 'p':
cout << "你选择的是pianist" << endl;
cout << "重新选择的话请重新输入,不重新选择的话请按q退出" << endl;
break;
case 't':
cout << "A maple is a tree" << endl ;
cout << "重新选择的话请重新输入,不重新选择的话请按q退出" << endl;
break;
case 'g':
cout << "你选择的是game" << endl ;
cout << "重新选择的话请重新输入,不重新选择的话请按q退出" << endl;
break;
case 'q':
return 1;
default:
cout << "please enter a,c,p,t,or g: ";
break;
}
}
return 0;
}
6.6 编写一个程序,记录捐助给"维护合法权利团体"的资金。该程序要求用户输入捐赠者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被存储在一个动态分配的结构数组中.每个数据结构有两个成员:用来存储姓名的字符串数组(或string对象)和用来存储款项的double成员。读取所有的数据后,程序将显示所有捐款超过10000的捐款着姓名及其捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。然后,程序将列出其他的捐款者,该列表要以Partons开头。如果某种类别没有捐款者,则程序将打印单词"none"。该程序只显示这两种类别,而不进行排序。
int main()
{
int num;
Person* pers = NULL;
cout << "请输入捐款人数量:";
cin >> num;
pers = new Person[num];
for (int i = 0; i < num; i++)
{
cout << "请输入第"<<i+1<<"位捐款人姓名:";
cin >> pers[i].fullname;
cout << "请输入第" << i+1 << "位捐款人捐款金额:";
cin >> pers[i].money;
}
cout << "Crand Patrons" << endl;
int pernum = 0;
for (int i = 0; i < num; i++)
{
if (pers[i].money > 10000)
{
cout << "捐款人姓名:" << pers[i].fullname << endl;
cout << "捐款人捐款金额:" << pers[i].money << endl;
pernum++;
}
}
if (pernum == 0)
{
cout << "NONE" << endl;
}
cout << "-----------" << endl;
cout << "Crand" << endl;
pernum = 0;
for (int i = 0; i < num; i++)
{
if (pers[i].money <= 10000)
{
cout << "捐款人姓名:" << pers[i].fullname << endl;
cout << "捐款人捐款金额:" << pers[i].money << endl;
pernum++;
}
}
if (pernum == 0)
{
cout << "NONE" << endl;
}
return 0;
}