C++ Primer Plus 第6版 第6章 编程练习答案

1. 编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写。(提示:cctype函数系列)

// 6-1
#include <iostream>
int main()
{
	using namespace std;
	char ch = 0;
	cout << "Enter some words: " << endl;
	while (cin.get(ch) && ch != '@') {  //逐个字母读取
		if (isdigit(ch))
			continue;
		else if (islower(ch))
			cout << char(toupper(ch));
		else if (isupper(ch))
			cout << char(tolower(ch));
		else cout << ch;
	}
	cout << endl;
	cout << "Done!\n";

	return 0;
}

2. 编写一个程序,最多将10个donation值读入到一个double数组中(或模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。

// 6-2
#include <iostream>
#include <array>
const unsigned int NUM = 10;
int main()
{
	using namespace std;
	array<double, NUM> donation;
	unsigned int enter = 0;
	double total_value = 0.0;
	double avg = 0.0;
	unsigned int large_avg = 0;

	cout << "Please enter up to ten double value, Non-digital to exit: \n";
	while (enter < 10 && (cin >> donation[enter])) {  //遇到非数字字符时,程序将挂起
		total_value += donation[enter];
		enter++;
	}

	avg = total_value / enter;
	for (int i = 0; i < enter; i++) {
		if (donation[i] > avg)
			large_avg++;
	}
	cout << "The average value is " << avg << ", and there are " << large_avg << " double value large than average value." << endl;

	return 0;
}

3. 编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行相应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单的操作。

// 6-3
#include <iostream>
#include <iomanip>

int main()
{
	using namespace std;
	cout << "Please enter one of the following choices: " << endl;
	cout << "c) carnivore \t p) pianist" << endl;
	cout << "t) tree \t g) game" << endl;
//	cout.flags(ios::left);
//	cout << setw(20) << "c) carnivore" << "p) pianist" << endl;
//	cout << setw(20) << "t) tree" << "g) game" << endl;
	char ch;
	bool exit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值