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

5.2 到 5.6

/* Ch5 exercise 2 to exercise 6 */
#include"std_lib_facilities.h"

double ctok(double c)
{
	/* c is celus temperature, it must bigger than -273.15 */
	if (c < -273.15)
		error("celus temperature must bigger than -273.15");
	return c + 273.15;
}

/* 5-5 */
double ktoc(double k)
{
	/* k is thermodynamic temperature, it must no less than 0.0 */
	if (k < 0.0)
		error("thermodynamic temperature must bigger than -273.15");
	return k - 273.15;
}

int main()
try
{
	double c = 0.0;
	cin >> c;
	/*5-3
	if (c < -273.15)
		error("celus must bigger than -273.15");
	*/
	double k = ctok(c);
	cout << k << " K\n";

	return 0;
}
catch (runtime_error& e)
{
	cerr << "runtime error: " << e.what() << '\n';
	return 1;
}
catch (...)
{
	cerr << "Some exceptions occured!\n";
	return 2;
}

5.7

/* quadratic equations of one unknown 
	design a function of quadratic formula
*/
#include"std_lib_facilities.h"

//我们还需要通过估计的方法,判断程序的结果是否合理,先设置一个允许误差 epsilon,判断所得的根是否超过误差。

static double epsilon{ 1.0e-7 };	//close enough to zero

double check(double x, double a, double b, double c)
{
	// check x against epsilon;
	// in case of a poor solution print a message to alert the user
	double e = a * x * x + b * x + c;

	if (e == 0.0)
		return x;
	else if (e > epsilon)
		cout << "poor root; off by " << e << '\n';	// positive and larger than epsilon
	else if (e < -epsilon)
		cout << "poor root; off by " << e << '\n';	// positive and larger than epsilon
	return x;
}

void quadratic_formula(double a, double b, double c)
{
	//solve the quadratic equation of one unknown
	if (a == 0)
	{
		if (b == 0.0 && c != 0.0)
			throw runtime_error("This is not a equation");
		else if (b == 0.0 && c == 0.0)
			cout << "There are infinity roots\n";
		else if (b != 0)
			cout << "root = " << check(-c / b, a, b, c) << '\n';
	}
	else
	{
		double delta = b * b - 4 * a * c;
		if (delta < 0)
			throw runtime_error("no real root");
		else if (delta == 0)
			cout << "root = " << check(-b / (2 * a), a, b, c)  << '\n';
		else
		{
			double x1{ 0.0 }, x2{ 0.0 };
			x1 = (-b - sqrt(delta)) / (2 * a);
			x2 = (-b + sqrt(delta)) / (2 * a);
			cout << "root1 = " << check(x1, a, b, c) << "\troot2 = " << check(x2, a, b, c) << '\n';
		}
	}
}

int main()
try
{
	cout << "Solve root(s) of quadratic equations of one unknown: ax^2 + bx + c = 0\n";
	cout << "Enter a, b, and c\n";
	double a, b, c;
	a = b = c = 0.0;
	while (cin >> a >> b >> c)
	{
		quadratic_formula(a, b, c);
		cout << "try again (enter a, b, c)\n";
	}
	return 0;
}
catch (runtime_error& e)
{
	cerr << "runtime_error: " << e.what() << '\n';
	return 1;
}

5.8 和 5.9

/* exercise 5_8 and 5_9 */
#include"std_lib_facilities.h"

class over_flow {};	// 专门报告溢出错误的类

void sum_n(vector<int>v, int n)
{
	if (n > v.size())
		throw runtime_error("the number of values you want to sum is more than the number of integers you entered");
	
	bool is_neg = false;
	int sum = 0;
	for (int i = 0; i < n; i++)
	{
		sum += v[i];
		//test if over flow
		if (sum < 0)
		{
			if (!is_neg && v[i] > 0)
				throw over_flow{};
			is_neg = true;
		}
		else
		{
			if (is_neg && v[i] < 0)
				throw over_flow{};
			is_neg = false;
		}
	}
	cout << "The sum of the first " << n << " numbers (";
	for(int i = 0; i < n; i++)
		cout << v[i] << ' ';
	cout << "\b) is " << sum << ".\n";
}

int main()
try
{
	cout << "Please enter the number of values you want to sum:\n";
	int n = 0;
	cin >> n;
	
	cout << "Please enter some integers (press '|' to stop):\n";
	vector<int>v;
	int num;
	while (cin >> num)
		v.push_back(num);
	sum_n(v, n);
	
	return 0;
}
catch (runtime_error& e)
{
	cerr << "runtime error: " << e.what() << '\n';
	return 1;
}
catch (over_flow)
{
	cerr << "Oops! The sum is over flow!\n";
	return 2;
}

5.10

/* exercise 5_8 and 5_9 */
#include"std_lib_facilities.h"

class over_flow {};	// 专门报告溢出错误的类

void sum_and_diff_n(vector<double>v, int n)
{
	if (n > v.size())
		throw runtime_error("the number of values you want to sum is more than the number of integers you entered");

	vector<double>diff;
	double sum = 0;
	for (int i = 0; i < n; i++)
	{
		sum += v[i];
		if (i > 0)
			diff.push_back(v[i - 1] - v[i]);
	}
	cout << "The sum of the first " << n << " numbers (";
	for (int i = 0; i < n; i++)
		cout << v[i] << ' ';
	cout << "\b) is " << sum << ".\n";

	cout << "The diff of " << n << " neighbor numbers: ";
	for (int i = 0; i < n - 1; i++)
		cout << diff[i] << ' ';
	cout << '\n';
}

int main()
try
{
	cout << "Please enter the number of values you want to sum:\n";
	int n = 0;
	cin >> n;

	cout << "Please enter some integers (press '|' to stop):\n";
	vector<double>v;
	double x;
	while (cin >> x)
		v.push_back(x);
	sum_and_diff_n(v, n);

	return 0;
}
catch (runtime_error& e)
{
	cerr << "runtime error: " << e.what() << '\n';
	return 1;
}
catch (over_flow)
{
	cerr << "Oops! The sum is over flow!\n";
	return 2;
}

5.11

/*斐波那契数列*/
#include"std_lib_facilities.h"

int main()
{
	int temp = 0;
	int fib = 1, prev_fib = 0;	//fib是当前斐波那契数,prev_fib是fib的前一个数

	while (1)
	{
		cout << fib << " ";
		temp = prev_fib + fib;
		if (temp <= 0)
			break;
		prev_fib = fib;
		fib = temp;
	}
	cout << "\nthe largest Fibonacci number that fits in an int is " << fib << '\n';

	return 0;
}

5.12 和 5.13

/* exercise 5-12 and 5-13 "bull and cow" game */

#include"std_lib_facilities.h"

int main()
try {
	cout << "At the beginning of this game, please enter an integer no lower than zero:\n";
	int seed{ 0 };
	
	do{
		cin >> seed;
		if (!cin)
			error("Oops! You input wrong, you should enter integer");
		if (seed >= 0)
			break;
		cout << "You should enter an ingeger no lower than zero:\n";
	} while (1);
	srand(seed);
	
	vector<int>random(4);
	unsigned int guess;
	unsigned int i = 0;
	unsigned int bulls = 0;
	unsigned int cows = 0;
	string choice{ "go" };

	cout << "Input g(go) to play game, or input q(quit) to quit\n";
	cin >> choice;
	if (!cin)
		error("Oops! You input wrong!");
	while (choice[0] == 'g')
	{
		for (i = 0; i < random.size(); i++)
			random[i] = randint(9);
		cout << "Please input four integers between 0 to 9\n";
		do {
			bulls = 0;
			cows = 0;
			for (i = 0; i < random.size(); i++)
			{
				cin >> guess;
				if (!cin)
					error("Oops! You input wrong, you should enter integer");
				for (unsigned j = 0; j < random.size(); j++)
					if (guess == random[j])
					{
						if (i == j)
							bulls++;
						else
							cows++;
					}
			}
			if (bulls == random.size())
			{
				cout << "Congratulations 4 bulls!\n";
				break;
			}
			else if (bulls < random.size())
			{
				cout << bulls << " bulls " << cows << " cows......\n";
				cout <<	"Input g(go) to try again, or input q(quit) to quit\n";
				cin >> choice;
				if (!cin)
					error("Oops! You input wrong!");
			}
		} while (choice[0] == 'g');
		cout << "Input g(go) to play next round, or input q(quit) to quit\n";
		cin >> choice;
		if (!cin)
			error("Oops! You input wrong!");
	}

	return 0;
}
catch (runtime_error& e)
{
	cerr << "runtime error: " << e.what() << '\n';
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为编写实际的应用程序做好准备:无论你是为了进行软件开发还是进行其他领域的工作。《C++程序设计原理实践(英文版)》假定你的最终目标是学会编写实际有用的程序。以基本概念和基本技术为重点:与传统的C++教材相比,《C++程序设计原理实践(英文版)》对基本概念和基本技术的介绍更为深入。这会为你编写有用、正确.易维护和有效的代码打下坚实的基础。, 用现代C++语言编程:, 《C++程序设计原理实践(英文版)》一方面介绍了通用的程序设计方法(包括面向对象程序设计和泛型程序设计)。另一方面还对软件开发实践中使用最广泛的程序设计语言——C++进行了很好的介绍。《C++程序设计原理实践(英文版)》从开篇就开始介绍现代C++程序设计技术,并介绍了大量关于如何使用C++标准库来简化程序设计的内容。, 适用于初学者以及任何希望学习新知识的人:, 《C++程序设计原理实践(英文版)》主要是为那些从未编写过程序的人编写的。而且已经由超过1000名大学一年级新生试用过。不过,对于专业人员和高年级学生来说,通过观察公认的程序设计大师如何处理编程中的各种问题。同样也会获得新的领悟和指引。, 提供广阔的视野:, 《C++程序设计原理实践(英文版)》第一部分非常广泛地介绍了基本程序设计技术,包括基本概念、设计和编程技术、语言特性以及标准库。这些内容教你如何编写具有输入、输出、计算以及简单图形显示等功能的程序。《C++程序设计原理实践(英文版)》第二部分则介绍了一些更专门性的内容(如文本处理和测试),并提供了大量的参考资料。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值