C++程序设计原理与实践 习题答案 第四章 第4章习题答案

4.2

#include"../../std_lib_facilities.h"

int main()
{
	vector<double>temps;
	for (double temp; cin >> temp;)
		temps.push_back(temp);

	// 计算温度的均值
	double sum = 0;
	for (double x : temps)
		sum += x;
	cout << "Average temperature: " << sum / temps.size() << '\n';

	// 计算温度的中值
	sort(temps);	// 将temps排序
	double mid_value;
	if (temps.size() % 2 == 1)
		mid_value = temps[temps.size() / 2];
	else
		mid_value = (temps[temps.size() / 2 - 1] + temps[temps.size() / 2]) / 2;
	cout << "Median temperature: " << mid_value << '\n';

	return 0;
}

4.3

#include"../../std_lib_facilities.h"

int main()
{
	constexpr double too_large{ 1000000.0 };
	vector<double> dist;
	double sum{ 0.0 };
	double min{ too_large };
	double max{ 0.0 };

	cout << "please enter a whitespace-separated sequence of doubles \
(representing distances)\n";
	cout << "terminate with a number <=0 or >" << too_large << " :\n";
	
	double val{ 0.0 };
	while (cin >> val)
	{
		if (val < 0 || val >= too_large)	//以提示方式(输入距离小于0或大于最大值)退出
			break;
		dist.push_back(val);
		sum += val;
		if (val < min)
			min = val;
		if (val > max)
			max = val;
	}

	if (dist.size() == 0)
		error("no distances");
	cout << "total distance: " << sum << '\n';
	cout << "smallest distance: " << min << '\n';
	cout << "greatest distance: " << max << '\n';
	cout << "mean distance: " << sum / dist.size() << '\n';
	return 0;
}

4.4

#include"../../std_lib_facilities.h"

int main()
{
	cout << "Set a integer between 1 to 100 and don't tell me.\n";
	cout << "Let me guess your integer. \
If I guess wrong, please input 'n', or input 'y'. Enter q to quit.\n";

	int min{ 1 };
	int max{ 100 };
	int guess{ 0 }, mid{ 0 };
	char in;

	do {
		mid = (min + max) / 2;
		if (guess != mid)
			guess = mid;
		else
			guess++;
		cout << "Is your number smaller than " << guess << " ?\n";
		cin >> in;
		if (in == 'y')
			max = guess - 1;
		else if (in == 'n')
			min = guess;
		else
		{
			cout << "Bye!\n";
			return 0;
		}
	} while (min < max);
	guess = (min + max) / 2;
	cout << "I know your number is " << guess << '\n';

	return 0;
}

//如果只问是否小于某个数这样的问题,两路判断,最坏情况是要问8次

4.5

#include"../../std_lib_facilities.h"

int main()
{
	cout << "please enter two floating-point values separated by an operator\n"
			"The operator can be + - * or / : ";
	double vala{ 0.0 };
	double valb{ 0.0 };
	char op{ 0 };

	while (cin >> vala >> op >> valb)
	{
		string oper;
		double sum{ 0.0 };
		switch (op) {
		case '+':
			oper = "The sum of ";
			sum = vala + valb;
			break;
		case '-':
			oper = "The difference between ";
			sum = vala - valb;
			break;
		case '*':
			oper = "The product of ";
			sum = vala * valb;
			break;
		case '/':
			oper = "The ratio of ";
			if (valb == 0)
			{
				cout << "Error: trying to divide by zero.\n";
				exit(0);
			}
			sum = vala / valb;
			break;
		//case '%':
		//	oper = "The remainder of ";
		//	sum = vala % valb;
		//  break;
		default:
			cout << "Error: invalid operator.\n";
			exit(0);
			break;
		}
		cout << oper << vala << " and " << valb << " is " << sum << '\n';
		cout << "Try again: ";
	}
	return 0;
}

4.6

#include"../../std_lib_facilities.h"

int main()
{
	vector<string> numbers {
		"zero", "one", "two", "three", "four", "five",
			"six", "seven", "eight", "nine", "ten"
	};

	int num_int{ 0 };
	string num_string{ "out of bound" };

	if (cin >> num_int)
	{
		if (num_int < numbers.size())
			num_string = numbers[num_int];
		cout << num_string << '\n';
	}
	else
	{
		cin.clear();
		cin >> num_string;
		size_t i;
		for (i = 0; i < numbers.size(); i++)
			if (num_string == numbers[i])
			{
				cout << i;
				break;
			}
		if (i >= numbers.size())
			cout << "unexpected number string: " << num_string << '\n';
	}
	return 0;
}

4.7

#include"../../std_lib_facilities.h"

int get_number(vector<string>);

int main()
{
	vector<string> numbers{
		"zero", "one", "two", "three", "four", "five",
			"six", "seven", "eight", "nine", "ten"
	};

	cout << "please enter two floating-point values separated by an operator\n"
		"The operator can be + - * or / : ";

	while (true)
	{
		double vala = get_number(numbers);
		char op{ 0 };
		cin >> op;
		double valb = get_number(numbers);

		string oper;
		double sum{ 0.0 };
		switch (op) {
		case '+':
			oper = "The sum of ";
			sum = vala + valb;
			break;
		case '-':
			oper = "The difference between ";
			sum = vala - valb;
			break;
		case '*':
			oper = "The product of ";
			sum = vala * valb;
			break;
		case '/':
			oper = "The ratio of ";
			if (valb == 0)
			{
				cout << "Error: trying to divide by zero.\n";
				exit(0);
			}
			sum = vala / valb;
			break;
			//case '%':
			//	oper = "The remainder of ";
			//	sum = vala % valb;
			//  break;
		default:
			cout << "Error: invalid operator.\n";
			exit(0);
			break;
		}
		cout << oper << vala << " and " << valb << " is " << sum << '\n';
		cout << "Try again: ";
	}

	return 0;
}

int get_number(vector<string>numbers)
{
	int size = numbers.size();
	const int not_a_symbol = size;
	int val{ not_a_symbol };

	if (cin >> val)
		return val;
	else
	{
		cin.clear();
		string num_string;
		val = not_a_symbol;
		cin >> num_string;
		for (int i = 0; i < size; i++)
			if (numbers[i] == num_string)
				val = i;
		if (val == not_a_symbol)
		{
			cout << "Error: unexpected number string: " << num_string << '\n';
			exit(0);
		}
		return val;
	}
}

4.8 和 4.9

#include"../../std_lib_facilities.h"

int main()
{
	constexpr int size{ 64 };
	long long rice_percell{ 1 };
	long long rice_sum{ 0 };
	long factor{ 2 };

	cout << "cell\trice per cell\t\trice sum\n";
	for (int i = 1; i <= 64; i++)
	{
		rice_sum += rice_percell;
		cout << i << '\t' << rice_percell << "\t\t" << rice_sum << '\n';
		rice_percell *= factor;
	}

	return 0;
}

4.10

#include"../../std_lib_facilities.h"

vector<int>fib{ 0,1 };
unsigned fib_index{ 0 };

void init_fib();
void extend_fib();
int next_play();

int main()
{
	constexpr int rock{ 0 };
	constexpr int paper{ 1 };
	constexpr int scissors{ 2 };

	init_fib();

	cout << "enter an integer \"seed\" to help me play: ";
	int seed = 0;
	cin >> seed;
	if (seed < 0)
		seed = -seed;
	fib_index = seed % 10;

	int count1 = 0;	// user's score
	int count2 = 0;	// computer's score
	int draws = 0;	// number of draws/ties

	cout << "enter \"rock\", \"paper\", or \"scissors\", enter q or quit to quit\n"
		<< "(I'll do the same and promises not to cheat by peeping at your input): ";
	string s;
	while (cin >> s)
	{
		// usr term
		int x{ rock };
		if (s == "scissors" || s == "s") {
			x = scissors;
			s = "scissors";
		}
		else if (s == "rock" || s == "r") {
			x = rock;
			s = "rock";
		}
		else if (s == "paper" || s == "p") {
			x = paper;
			s = "paper";
		}
		else if (s == "quit" || s == "q")
			break;
		else
		{
			cout << "Sorry: bad operator: " << s << ", please try again.\n";
			continue;
		}

		// computer term
		int xx = next_play();
		string ss;
		switch (xx) {
		case rock:
			ss = "rock";
			break;
		case paper:
			ss = "paper";
			break;
		case scissors:
			ss = "scissors";
			break;
		}
		if (x == xx)	//平局
		{
			cout << "a draw!\n";
			draws++;
		}
		else
		{
			string res = "I win!";
			if ((x == rock && xx == scissors) ||
				(x == paper && xx == rock) || (x == scissors && xx == paper))
			{
				res = "You win!";
				count1++;
			}
			else
				count2++;

			cout << "you said \"" << s << "\" I said \"" << ss << "\": " << res;
			cout << " score: you==" << count1 << " me==" << count2 
				 << " same==" << draws << "\n";
		}
		cout << "Please try again: ";
	}
	cout << "Bye!\n";

	return 0;
}


void init_fib()
{
	extend_fib();
}

void extend_fib()
{
	constexpr int init_size{ 20 };
	int extend = fib.size() + init_size;
	int val{ 0 };

	for (int i = fib.size(); i <= extend; i++)
	{
		val = fib[i - 1] + fib[i - 2];
		fib.push_back(val);
	}
}

int next_play()
{
	if (fib_index >= fib.size())
		extend_fib();
	return fib[fib_index++] % 3;
}

4.11 求素数的一种方法

#include"../../std_lib_facilities.h"

vector<int>primes{ 2 };
bool is_prime(int);

int main()
{
	for (int i = 3; i < 100; i += 2)
		if (is_prime(i))
			primes.push_back(i);
	
	cout << "All primes between 1-100 are below:\n";
	for (int x : primes)
		cout << x << "    ";

	return 0;
}

bool is_prime(int num)
{
	for (int x : primes)
		if (num % x == 0 && x < num)
			return false;
	return true;
}

4.13

#include"../../std_lib_facilities.h"

int main()
{
	// 首先进行初始化
	vector<int>arr(100);
	for (int i = 2; i <arr.size(); i++)
		arr[i] = 1;

	for (int i = 2; i < arr.size(); i++)
		if (arr[i])
			for (int j = i + i; j < arr.size(); j += i)
				arr[j] = 0;
	cout << "Primes: \n";
	for (int i = 2; i < arr.size(); i++)
		if (arr[i])
			cout << i << "  ";

	return 0;
}

4.15

#include"../../std_lib_facilities.h"

vector<int> primes{ 2 };

bool is_prime(int);

int main()
{
	cout << "Enter an integer n, I will output the first n primes.\n";

	int n;
	cin >> n;

	for (int i = 0, j = 2; i < n; i++)
	{
		cout << primes[i] << "  ";
		while(++j)
			if (is_prime(j))
			{
				primes.push_back(j);
				break;
			}
	}

	return 0;
}

bool is_prime(int num)
{
	for (int x : primes)
		if (num % x == 0 && x < num)
			return false;
	return true;
}

4.16

#include"../../std_lib_facilities.h"

int main()
{
	vector<int> mode;
	int mode_cnt{ 0 };
	int candidate{ -1 };
	int cnt{ 0 };
	vector<int>nums;

	cout << "Enter some positive integers\n";
	int x;
	while (cin >> x)
		if (x > 0)
			nums.push_back(x);

	sort(nums);		//首先排序

	for (int x : nums)
		if (candidate == x)
			cnt++;
		else
		{
			if (cnt > mode_cnt)
			{
				mode.clear();
				mode.push_back(candidate);
				mode_cnt = cnt;
			}
			else if (cnt == mode_cnt)
				mode.push_back(candidate);
			candidate = x;
			cnt = 1;
		}
	if (cnt > mode_cnt)
	{
		mode.clear();
		mode.push_back(candidate);
		mode_cnt = cnt;
	}
	else if (cnt == mode_cnt)
		mode.push_back(candidate);

	cout << "Max: " << nums[nums.size() - 1] << '\n';
	cout << "Min: " << nums[0] << '\n';
	cout << "Mode: ";
	for (int x : mode)
		cout << x << ' ';
	cout << '\n';

	return 0;
}

4.18

#include"../../std_lib_facilities.h"

int main()
{
	cout << "Quadratic equation is like ax^2 + bx + c = 0\n";
	cout << "Enter a, b and c seperated by sapce\n";

	double a, b, c;
	cin >> a >> b >> c;
	double delta = b * b - 4 * a * c;

	if (delta > 0)
	{
		double x1, x2;
		x1 = (-b - sqrt(delta)) / (2 * a);
		x2 = (-b + sqrt(delta)) / (2 * a);
		cout << "Root1: " << x1 << '\n';
		cout << "Root2: " << x2 << '\n';
	}
	else if (delta == 0)
	{
		double x;
		x = -b / (2 * a);
		cout << "Only one root: " << x << '\n';
	}
	else
		cout << "No root\n";

	return 0;
}

4.19

#include"../../std_lib_facilities.h"

int main()
{
	vector<string>names;
	vector<int>scores;

	cout << "Enter name scores pairs, enter no more0 to end.\n";
	string nm;
	int sc;
	while (cin >> nm >> sc)
	{
		for (string s : names)
			if (s == nm)
			{
				cout << "Error: duplicate: " << nm << '\n';
				exit(0);
			}
		names.push_back(nm);
		scores.push_back(sc);
	}
	for (int i = 0; i < names.size(); i++)
		cout << names[i] << ' ' << scores[i] << '\n';

	return 0;
}

4.20

#include"../../std_lib_facilities.h"

int main()
{
	vector<string>names;
	vector<int>scores;

	cout << "Enter name scores pairs, enter NoMore 0 to end.\n";
	string nm;
	int sc;
	while (cin >> nm >> sc && nm != "NoMore")
	{
		for (string s : names)
			if (s == nm)
			{
				cout << "Error: duplicate: " << nm << '\n';
				exit(0);
			}
		names.push_back(nm);
		scores.push_back(sc);
	}

	cout << "Enter name and I give you score of him/hers\n, enter q to quit";
	int i;
	while (cin >> nm)
	{
		if (nm == "q")
			break;
		for (i = 0; i < names.size(); i++)
			if (nm == names[i])
			{
				cout << scores[i] << '\n';
				break;
			}
		if (i == names.size())
			cout << "name not found.\n";
	}

	return 0;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值