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

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。故假设不成立,原命题成立。


3-2. Write a program to compute and print the quartiles (that is, the quarter of the numbers with the largest values, the next highest quarter, and so on) of a set of integers.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
	int n;
	vector<int> vec;
	cout<<"input the num:"<<endl;
	while(cin>>n)
		vec.push_back(n);
	sort(vec.rbegin(),vec.rend());

	typedef vector<int>::size_type size_tp;
	size_tp size=vec.size();
	int block=size/4;

	for(int i=0,j=0;i!=size;++i)
	{
		if(i%block==0)
		{
			++j;
			cout<<endl<<"block "<<j<<"is:"<<endl;
		}
		cout<<vec[i]<<'\t';
	}
	cout<<endl;

	return 0;
}
lyj@qt:~/Desktop$ g++ 3-2.cpp -o 3-2
lyj@qt:~/Desktop$ ./3-2
input the num:
4
5
6
7
8
9
0
1
2
33
12
14
1
61
19
20
block 1 is:
61 33 20 19
block 2 is:
14 12 9 8
block 3 is:
7 6 5 4
block 4 is:
2 1 1 0
lyj@qt:~/Desktop$ 

3-3. Write a program to count how many times each distinct word appears in its input. 

Ans:本题用关联容器解决比较简单,map<key,value>其中key存储为单词,value为该单词出现次数,将输入的单词按key索引++map[key]存储,即可。具体实现如下:

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
	string word;
	int value;
	map<string,int> vec;
	cout<<"input the words:"<<endl;
	while(cin>>word)
	{
		++vec[word];
	}
	for(map<string,int>::const_iterator it=vec.begin();
		it!=vec.end();++it)
	{
		cout<<it->first<<" input "<<it->second<<" times"<<endl;
	}

	return 0;
}
lyj@qt:~/Desktop$ g++ 3-3.cpp -o 3-3
lyj@qt:~/Desktop$ ./3-3
input the words:
I am a boy I am a girl
I input 2 times
a input 2 times
am input 2 times
boy input 1 times
girl input 1 times
lyj@qt:~/Desktop$ 

3-4. Write a program to report the length of the longest and shortest string in its input.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
	vector<string> vec;
	string str;
	cout<<"input a strings:"<<endl;
	while(cin>>str)
		vec.push_back(str);
	vector<string>::const_iterator it=vec.begin();
	int min=(*it).size(),max=0;
	for(;it!=vec.end();++it)
	{
		int size=(*it).size();
		if(size>max)
			max=size;
		if(min>size)
			min=size;
	}

	cout<<"min="<<min<<"\nmax="<<max<<endl;
	return 0;
}
lyj@qt:~/Desktop$ g++ 3-4.cpp -o 3-4
lyj@qt:~/Desktop$ ./3-4
input a strings:
I am a very handsome boy , you konw?
min=1
max=8
lyj@qt:~/Desktop$ 

3-5. Write a program that will keep track of grades for several students at once. The program could keep two vectors in sync: The first should hold the student's names, and the second the final grades that can be computed as input is read. For now, you should assume a fixed number of homework grades. We'll see in §4.1.3/56 how to handle a variable number of grades intermixed with student names.

#include <iostream>
#include <vector>
#include <string>
#define H 3//家庭作业成绩的个数
using namespace std;
int main()
{
	unsigned int n;//学生个数n
	cout<<"input the total stu nums:";
	cin>>n;
	if(n<=0)
	{
		cout<<"n must be an unsigned int!"<<endl;
		return 1;
	}

	vector<string> vecName;
	vector<double> vecScore;
	while(n>0)
	{
		string name;
		double midterm,fin,homework;
		double hwScore=0,total=0;
		int k=0;
		cout<<"input name:";
		cin>>name;
		vecName.push_back(name);//name
		cout<<endl<<"input midterm & final score:";
		cin>>midterm>>fin;

		cout<<endl<<"input homework score:"<<endl;
		while( k<H && (cin>>homework) )
		{
			hwScore+=homework;
			++k;
		}
		total=0.4*fin+0.2*midterm+0.4*(hwScore/k);
		vecScore.push_back(total);//total score

		--n;
	}
	typedef vector<double>::size_type size_tp;
	size_tp size=vecScore.size();
	for(int i=0;i!=size;++i)
	{
		cout<<vecName[i]<<"-----"<<vecScore[i]<<endl;
	}
	return 0;
}
tianya@git:~/Desktop$ g++ 3-5.cpp -o 3-5
tianya@git:~/Desktop$ ./3-5
input the total stu nums:2
input name:tianya
input midterm & final score:99 98
input homework score:99 98 99
input name:tony
input midterm & final score:98 97
input homework score:89 90 99
tianya-----98.4667
tony-----95.4667
tianya@git:~/Desktop$ 


3-6. The average-grade computation in §3.1/36 might divide by zero if the student didn't enter any grades. Division by zero is undefined in C++, which means that the implementation is permitted to do anything it likes. What does your C++ implementation do in this case? Rewrite the program so that its behavior does not depend on how the implementation treats division by zero.

Ans:不能除0,那么C++实现中需要有一个对count的判断,当count=0时,退出程序并输出一段字符串提示原因。

#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    // ask for and read the student's name
    cout << "Please enter your first name: ";
    string name;
    cin >> name;
    cout << "Hello, " << name << "!" << endl;

    // ask for and read the midterm and final grades
    cout << "Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    // ask for the homework grades
    cout << "Enter all your homework grades, "
	        "followed by end-of-file: ";

    // the number and sum of grades read so far
    int count = 0;
    double sum = 0;

    // a variable into which to read
    double x;

    // invariant:
    // we have read count grades so far, and
    // sum is the sum of the first count grades
    while (cin >> x) {
        ++count;
        sum += x;
    }
    if(0==count)
    {
	cout<<endl<<"this student hadn't done the homework!"<<endl;
	return 1;
    }

    // write the result
    streamsize prec = cout.precision();
    cout << "Your final grade is " << setprecision(3)
         << 0.2 * midterm + 0.4 * final + 0.4 * sum / count
         << setprecision(prec) << endl;

    return 0;
}

tianya@git:~/Desktop$ g++ 3-6.cpp -o 3-6
tianya@git:~/Desktop$ ./3-6
Please enter your first name: tianya
Hello, tianya!
Please enter your midterm and final exam grades: 99 98
Enter all your homework grades, followed by end-of-file: 
this student hadn't done the homework!
tianya@git:~/Desktop$ 


你可能感兴趣的:(C++,C++,Accelerated,Accelerated,通过示例进行编程实践,C++习题解答)