Accelerated C++:通过示例进行编程实践——练习解答(第3章)

本文详细解答了Accelerated C++书中第3章的若干编程问题,包括如何证明在未知数量的数值集合中不能丢弃已读取的中位数,编写计算并打印整数集合四分位数的程序,以及避免在计算平均成绩时遇到除以零错误的方法。示例代码展示了具体的解决方案。
摘要由CSDN通过智能技术生成

3-0. Compile, execute, and test the programs in this chapter.

#include <iostream>
#include <vector>
#include <ios>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
	cout<<"input name:";
	string name;
	cin>>name;
	cout<<endl;

	cout<<"input your midterm & final score:";
	double midterm,fin;
	cin>>midterm>>fin;
	cout<<endl;

	cout<<"input your homework scores:"<<endl;
	vector<double> homework;
	double hw;
	while(cin>>hw)
	{
		homework.push_back(hw);
	}
	cout<<endl;

	sort(homework.begin(),homework.end());//sort the homework score
	typedef vector<double>::size_type size_tp;
	size_tp size=homework.size();//homework size
	int mid=size/2;
	double mid_hw=size%2==0?(homework[mid-1]+homework[mid])/2:homework[mid];
	
	streamsize proc=cout.precision();
	cout<<setprecision(4)<<"the score is:"<<0.4*fin+0.4*mid_hw+0.2*midterm<<
		setprecision(proc)<<endl;
	return 0;
}
lyj@qt:~/Desktop$ g++ 3-0.cpp -o 3-0
lyj@qt:~/Desktop$ ./3-0
input name:tianya
input your midterm & final score:98 99
input your homework scores:
99
100
98
97
99
100
the score is:98.8
lyj@qt:~/Desktop$ 

3-1. Suppose we wish to find the median of a collection of values. Assume that we have read some of the values so far, and that we have no idea how many values remain to be read. Prove that we cannot afford to discard any of the values that we have read. Hint: One proof strategy is to assume that we can discard a value, and then find values for the unread—and therefore unknown—part of our collection that would cause the median to be the value that we discarded.

Ans:根据题中假设证明,假设输入8,10,11,15时丢弃一数值15,然后继续读入剩余数值16,17,此时数据集合为8,10,11,16,17,中值为11,而不等于丢掉的值15。故假设不成立,原命题成立。</

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值