【C++Primer5】第一章的练习题及答案
1.1 Review the documentation for your compiler and determine what file naming convention it uses. Compile and run the main program from page 2.
大意:学习一下如何使用你的编译器
赶紧学习一下!
1.2 Change the program to return -1. A return value of -1 is often treated as an indicator that the program failed. Recompile and rerun your program to see how your system treats a failure indicator from main.
大意:尝试在main函数中返回-1,看看会怎么样
会怎么样,也不会怎么样。这里就是解释了return 0是表示程序运行正常的意思,return -1是表示程序运行错误的意思。一般如果程序运行正常,return 0是可以不写的
1.3 Write a program to print Hello, World on the standard output.
大意:打印你好,世界
#include <iostream>using namespace std;int main()
{cout << "Hello, World" << endl;
}
1.4 Our program used the addition operator, +, to add two numbers. Write a program that uses the multiplication operator, *, to print the product instead.
大意:我们的程序打印了两个数的和,现在写一个程序打印两个数的积
首先我们需要知道,原本的程序是怎么写的
#include <iostream>// 注意:这段代码不是我写的,是c++ primer书中给出的
// 但是我们可以来学习一下大师的代码,是怎么样的int main()
{// 首先,第一步就非常厉害,用了一个逗号分隔符,同时声明了2个变量int v1 = 0, v2 = 0;// 没有使用using namespace,而是使用了std::代替,避免出现重名问题// 在cin这一步中,使用了一个链式调用,简单便捷std::cin >> v1 >> v2;// 由于下面代码太长了,不适合阅读,于是对其进行了分段处理,方便阅读std::cout << "The sum of " << v1 << " and " << v2<< " is " << v1 + v2 << std::endl;// 由此可见,大师的代码果然让人受益匪浅
}
那么,我们如何来模仿一下呢,毕竟抄代码是非常容易的
#include <iostream>int main()
{int v1 = 0, v2 = 0;std::cin >> v1 >> v2;std::cout << "The multiplication of " << v1 << " and " << v2<< " is " << v1 * v2 << std::endl;
}
由此可见,跟大师学习,你的代码也可以变得非常厉害!
1.5 We wrote the output in one large statement. Rewrite the program to use a separate statement to print each operand.
大意:我们的输出语句太长了,给它写成单独的语句
说实话没太懂,是想说把输出语句拆开吗?那应该不是很难吧
1.6 Explain whether the following program fragment is legal.
// 以下代码为c++ primer书中提供的练习题 std::cout << "The sum of " << v1;<< " and " << v2;<< " is " << v1 + v2 << std::endl;
If the program is legal, what does it do? If the program is not legal, why not? How would you fix it?
大意:看看这段代码正确吗?如何修正呢?
这个代码明显有问题,主要在于第一句末尾添加了分号结束了,因此和第二段连不上了,把第一句末尾的分号去掉就好了(假设我们不考虑前边是否定义过v1和v2的话)。
1.7 Compile a program that has incorrectly nested comments.
大意:编译一个不正确的嵌套注释的程序
这个题目想说多行注释不能嵌套调用,理由也很简单,因为内部的注释的开头会被当成注释,但是内部的注释的结尾会被当成外边的注释的结束
1.8 Indicate which, if any, of the following output statements are legal:
std::cout << "/*"; std::cout << "*/"; std::cout << /* "*/" */; std::cout << /* "*/" /* "/*" */;
After you've predicted what will happen, test your answers by comiling a program with each of these statements. Correct any errors you encounter.
大意:看看这几个语句,哪一个是对的
第一个明显是对的,/*是一个字符串
第二个明显也是对的,*/是一个字符串
第三个肯定不太对,第一个/*是一个注释,到第二个*/结束的时候,把一个引号注释掉了,就剩下了一个引号,这个肯定不对
第四个有点麻烦,第一个/*是一个注释,到第二个*/注释掉了一个引号,然后是一个字符串,到第二个/*都是字符串,然后字符串结束了是一个注释,注释到最后一个*/又注释掉了一个引号。所以说绕了一圈,这个是对的
说句实话,这一看就不像是一个正常人写的出来的代码。。
1.9 Write a program that uses a while to sum the numbers from 50 to 100.
大意:用while循环从50加到100
#include <iostream>using namespace std;int main()
{int num = 50;int total = 0;while (num <= 100){total += num;++num;}cout << total << endl;
}
1.10 In addition to the ++ operator that adds 1 to its operand, there is a decrement operator(--) that subtracts 1. Use the decrement operator to write a while that prints the numbers from ten down to zero.
大意:写一个while循环,从10加到0
其实和刚刚差不多,没什么变化
#include <iostream>using namespace std;int main()
{int num = 10;int total = 0;while (num >= 0){total += num;--num;}cout << total << endl;
}
1.11 Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
大意:输入两个数,打印这两个数之间的数
这里面有两个问题,输入两个数,到底是哪个数比较大一点呢?打印的顺序必须按照输入的顺序来吗?
如果可以自行更换顺序,那么我们只需要先比较两个数的大小,然后再按照同一个方法打印即可,如果是按照输入的顺序的话,那么我们不能这么做
总之,使用if判断加while循环即可
#include <iostream>using namespace std;int main()
{// 因为书中使用了v1,v2,因此这里我也是这么用的// 之所以书中会起名为v,大概是变量的意思int v1, v2;cin >> v1 >> v2;if (v1 >= v2)while (v1 >= v2){cout << v1 << endl;--v1;}elsewhile (v1 <= v2){cout << v1 << endl;++v1;}
}
1.12 What does the following for loop do? What is the final value of sum?
int sum = 0; for (int i = -100; i <= 100; ++i)sum += i;
大意:这段代码的运行结果是什么?
这是一个for循环,从-100一直加到了100,显然结果为0
1.14 Rewrite the exercises from 1.4.1 using for loops.
大意:重写1.4.1的内容,1.4.1大概是指1.9,1.10和1.11
我们将1.9-1.11的代码整个复制过来,然后改动一下即可
新1.9 使用for循环从50加到100
#include <iostream>using namespace std;int main()
{int total = 0;for (int num=50; num <= 100; ++num)total += num;cout << total << endl;
}
新1.10 使用for循环从10加到0
#include <iostream>using namespace std;int main()
{int total = 0;for (int num=10; num >=0; --num)total += num;cout << total << endl;
}
新1.11 输入两个数,通过for循环打印这两个数之间的数
#include <iostream>using namespace std;int main()
{int v1, v2;cin >> v1 >> v2;if (v1 >= v2)for (; v1>=v2; --v1)cout << v1 << endl;elsefor (; v1<=v2; ++v1)cout << v1 << endl;
}
1.14 Compare and contrast the loops that used a for with those using a while. Are there advantages or disadvantages to using either form?
大意:对比一下for循环和while循环,哪个更好用?
for循环可以完全替代while循环,当然while循环也可以完全替代for循环,使用哪个完全看个人喜好,本质上没有太大的差别。当然一般而言,习惯上已知循环次数的可以考虑优先使用for循环,不知道循环次数的可以优先使用while循环。一般来说,如果要创建一个无限循环,使用for(;;)的要多于while (true),当然无限循环并不是什么好主意
1.15 Write programs that contain the common errors discussed in the box on page 16. Familiarize yourself with the messages the compiler generates.
大意:编写包含常见错误的程序,熟悉一下你的编译器是怎么报错的
我觉得不用专门编写错误,只要正常写程序,就全都是错误
1.16 Write your own version of a program that prints the sum of a set of integers read from cin.
大意:编写你自己的程序,通过cin接受数字,然后求和
俗话说,1000个人学c++就能编写出1000中不同的hello world,emmm,真的有人这样说吗?
1.17 What happens in the program presented in this section if the input values are all equal? What if there are no duplicated values?
大意:如果输入的值都相等,程序的运行结果会怎样?如果输入的值都不同,又会怎样
// 以下为题目中所指的程序 // 注意:以下所有的代码,包括注释,都不是我写的,均为c++ primer 5书中原本的代码 // 我尽量将其完整的还原了,以供诸位可以欣赏到原版的代码#include <iostream> int main() {// currVal is the number we're counting; we'll read new values into valint currVal = 0, val = 0;// read first number and ensure that we have data to processif (std::cin >> currVal) {int cnt = 1; // store the count for the current value we're processingwhile (std::cin >> val) { // read the remaining numbersif (val == currVal) // if the values are the same++cnt; // add 1 to cntelse { // otherwise, print the count for the previous valuestd::cout << currVal << " occurs "<< cnt << " times" << std::endl;currVal = val; // remember the new valuecnt = 1; // reset the counter}} // while loop ends here// remember to print the count for the last value in the filestd::cout << currVal << " occurs "<< cnt << " times" << std::endl;} // outermost if statement ends herereturn 0; }
如果输入的值都一样会怎么样,会导致屏幕总是不出现打印结果
如果输入的值都不一样会怎么样,会导致屏幕总是打印这个值出现了1次
另外,多提一句,这个代码本身,是非常非常优秀的。包括注释在内,都控制了字数可以在1屏之内显示。代码段的风格是混用了次行和末行,主要表现在主函数main使用次行,小型的if和while的代码段使用了末行。if和while的括号和花括号之间均有空格,而且注释写的非常完整而详细,可以说,是值得模仿学习的代码。
1.18 Compile and run the program from this section giving it only equal values as input. Run it again giving it values in which no number is repeated.
大意:运行一下1.17的代码,看看实际结果是怎样的
复制1.17的程序运行即可
1.19 Revise the program you wrote for the exercises in 1.4.1 that printed a range of numbers so that it handles input in which the first number is smaller than the second.
大意:重写1.11中的程序,使其可以处理第一个数比第二个数要小的情况
这个我在写1.11的时候已经处理过了,因此无需重写了
1.20 http://www.informit.com/title/032174113 contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that file to your working directory. Use it to write a program that reads a set of book sales transactions, writing each transaction to the standard output.
大意:在这个网站上下载一个头文件,并尝试使用它来一次性读取一些书籍的销售记录,并输出
首先,我们需要找到"Sales_item.h"这个头文件。
// 程程补充的注释:以下的所有代码都不是我写的,是C++ Primer的书籍中给出的!/*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*//* This file defines the Sales_item class used in chapter 1.
* The code used in this file will be explained in
* Chapter 7 (Classes) and Chapter 14 (Overloaded Operators)
* Readers shouldn't try to understand the code in this file
* until they have read those chapters.
*/#ifndef SALESITEM_H
// we're here only if SALESITEM_H has not yet been defined
#define SALESITEM_H// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>class Sales_item {// these declarations are explained section 7.2.1, p. 270 // and in chapter 14, pages 557, 558, 561friend std::istream& operator>>(std::istream&, Sales_item&);friend std::ostream& operator<<(std::ostream&, const Sales_item&);friend bool operator<(const Sales_item&, const Sales_item&);friend booloperator==(const Sales_item&, const Sales_item&);
public:// constructors are explained in section 7.1.4, pages 262 - 265// default constructor needed to initialize members of built-in type#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)Sales_item() = default;#elseSales_item() : units_sold(0), revenue(0.0) { }#endifSales_item(const std::string &book) :bookNo(book), units_sold(0), revenue(0.0) { }Sales_item(std::istream &is) { is >> *this; }
public:// operations on Sales_item objects// member binary operator: left-hand operand bound to implicit this pointerSales_item& operator+=(const Sales_item&);// operations on Sales_item objectsstd::string isbn() const { return bookNo; }double avg_price() const;// private members as before
private:std::string bookNo; // implicitly initialized to the empty string#ifdef IN_CLASS_INITSunsigned units_sold = 0; // explicitly initializeddouble revenue = 0.0;#elseunsigned units_sold;double revenue;#endif
};// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs)
{return lhs.isbn() == rhs.isbn();
}// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);inline bool
operator==(const Sales_item &lhs, const Sales_item &rhs)
{// must be made a friend of Sales_itemreturn lhs.units_sold == rhs.units_sold &&lhs.revenue == rhs.revenue &&lhs.isbn() == rhs.isbn();
}inline bool
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{return !(lhs == rhs); // != defined in terms of operator==
}// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{units_sold += rhs.units_sold;revenue += rhs.revenue;return *this;
}// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{Sales_item ret(lhs); // copy (|lhs|) into a local object that we'll returnret += rhs; // add in the contents of (|rhs|) return ret; // return (|ret|) by value
}std::istream&
operator>>(std::istream& in, Sales_item& s)
{double price;in >> s.bookNo >> s.units_sold >> price;// check that the inputs succeededif (in)s.revenue = s.units_sold * price;elses = Sales_item(); // input failed: reset object to default statereturn in;
}std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{out << s.isbn() << " " << s.units_sold << " "<< s.revenue << " " << s.avg_price();return out;
}double Sales_item::avg_price() const
{if (units_sold)return revenue / units_sold;elsereturn 0;
}
#endif
将以上的代码复制,即可得到Sales_item.h这个头文件。之后我们的任务就是尝试去使用它。
虽然编写这个程序看起来是很困难的,但是使用这个程序是很简单的事情,按照题目要求,我们只需要这样做就好了
#include <iostream>
#include "Sales_item.h"using namespace std;int main()
{Sales_item book;while(cin >> book)cout << book << endl;return 0;
}
输入0-201-70353-X 4 24.99
输出0-201-70353-X 4 99.96 24.99
输入的是书的标记, 本数和价格,输出是标记,本书,总价和价格
这就是了不起的c++的精神了,使用者无需知道原作者的代码中内部是如何实现的,也不应该去改动原作者的代码,只要知道原作者所留给你的接口和使用方法就行了
1.21 Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.
大意:输入两个相同ISBN的书籍,输出他们的和
#include <iostream>
#include "Sales_item.h"using namespace std;int main()
{Sales_item book1, book2;cin >> book1 >> book2;cout << book1 + book2 << endl;return 0;
}
输入0-201-78345-X 3 20.00
输入0-201-78345-X 4 25.00
输出0-201-78345-X 7 160 22.8571
1.22 Write a program that reads several transactions for the same ISBN. Write the sum of the transactions that were read.
大意:输入多个相同ISBN,输出他们的和
#include <iostream>
#include "Sales_item.h"using namespace std;int main()
{Sales_item total;cin >> total;Sales_item new_book;while (cin >> new_book)if (total.isbn() == new_book.isbn())total += new_book;else{cerr << "错误:输入的ISBN不相同" << endl;return -1;}cout << total;return 0;
}
1.23 Write a program that reads several transactions and counts how many transactions occur for each ISBN.
大意:统计每个ISBN的记录出现了几次
// 这是一种实现的方法,但是不是很好#include <iostream>
#include <vector>
#include <string>
#include "Sales_item.h"using namespace std;int main()
{vector<string> books; // 首先建立一个ISBN的数组vector<int> books_num; // 然后建立一个出现次数的数组Sales_item book;bool flag;while (cin >> book){for (int i=0; i<books.size(); ++i){flag = true;if (book.isbn() == books[i]){books_num[i] += 1;flag = false;break;}}if (flag){books.push_back(book.isbn()); // 如果这两个数组的数据一一对应books_num.push_back(1); // 那么就相当于第二个数组记录了第一个数组的本数}}for (int i=0; i<books.size(); ++i)cout << books[i] << ": " << books_num[i] << endl;
}
1.24 Test the previous program by giving multiple transactions representing multiple ISBNS. The records for each ISBN should be grouped together.
大意:测试1.23中的程序
正常流程的测试应该首先创建多条记录,然后尝试输入
1.25 Using the Sales_item.h header from the Web site, compile and execute the bookstore program presented in this section.
大意:使用Sales_item.h头文件,编译书店程序
书店程序的代码如下,这些代码出自c++ primer 5 1.6节
// 程程补充注释:以下代码都不是我写的,全都出自c++primer5
// 我尝试将其完整的还原了出来,以供各位可以看到原作者写的代码#include <iostream>
#include "Sales_item.h"
int main()
{Sales_item total; // variable to hold data for the next transaction// read the first transaction and ensure that there are data to processif (std::cin >> total) {Sales_item trans; // variable to hold the running sum// read and process the remaining transactionswhile (std::cin >> trans) {// if we're still processing the same bookif (total.isbn() == trans.isbn())total += trans;else {// print results for the previous bookstd::cout << total << std::endl;total = trans; // total now refers to the next book}}std::cout << total << std::endl; // print the last transaction} else {// no input! warn the userstd::cerr << "No data?!" << std::endl;return -1; // indicate failure}return 0;
}
简单的分析一下,我们可以看出,大师的代码中有一个很明显的特点,就是任何时候,都不会使用using namespace std;
除此之外,我们还可以观察到一件事情,就是代码中对于没有输入数据的这种情况做了处理。按照常理来说,之前我们在练习1.20-1.23中的代码,也应该加入对于没有数据的处理和提醒。但是我没有这样,所以说要注意这一点。如果真的有读者读到了这里的话,我建议你可以根据以上代码,对之前的代码作出修正。
第一章终于结束了!从开始写第一章的习题答案,到最终完结,差不多用了2周的时间。写文章真的很不容易,而完成像c++ primer这样的巨著,就更是要困难百倍。好好珍惜这些书籍吧,这都是伟大的作者花费数年的心血才完成的!可是,很多人只想看盗版书,一分钱也不愿意花。如果你现在处于困境,身无分文,看盗版书籍学习也是可以理解的。但是有朝一日,你赚到了钱,至少生活上不再那么紧张了,为这些正版的书籍作者补个票吧!这大概就是对作者心血的最好的支持了。
我一刻都不能停止,因为clion还在等着我给他付钱呢,纵使我从c++上从未有赚到过任何一分钱。By:程程之光 2021-09-09
【C++Primer5】第一章的练习题及答案相关推荐
- c语言第三章作业题答案,c语言第三章简单练习题及答案.doc
c语言第三章简单练习题及答案 c语言第三章简单练习题及答案 一.选择题 1. C语言提供的合法的数据类型关键字是. Double shortinteger Char 2. 在C语言中,合法的长整型常数 ...
- c语言上机指导答案清华,第一章自测练习答案清华大学c语言习题实验指导及课程设计...
第一章自测练习答案清华大学c语言习题实验指导及课程设计 第一章 自测练习参考答案 一.简答题 1.源程序是程序员创建的,目标程序是编译器创建的,可执行程序是连接器创建的. 2.步骤如下:1)说明程序需 ...
- 计算机课第一章答案,计算机应用基础第一章课后习题参考答案答案
计算机应用基础第一章课后习题参考答案答案 第1章 课后习题 一.简答题: 1.电子计算机的发展大致可分哪几代?请说出各个时代电子计算机的特点. 1. 第一代电子计算机 第一代电子计算机是电子管计算机, ...
- c++ primer5 第一章练习题答案 尚未完成 后续补充(基本已经完结)
1.3 //1.3 #include <iostream>//如果加上这一行就不需要 std::cout 直接cout就可以了总是忘记 加std 这里出于和书籍 上代码配套 所以还是 st ...
- 第一章课后习题及答案
第一章习题及答案 转载于:https://www.cnblogs.com/hhdn/archive/2007/02/28/659587.html
- 操作系统--第一章 操作系统引论--习题答案
操作系统第四版课后的全部习题答案,学习通作业答案. 说明:操作系统其他章节的习题答案也在此"操作系统"专栏. 第一章 1.设计现代OS的主要目标是什么?== 答:(1)有效性 (2 ...
- 数据库系统概念原书第六版黑皮书第一章课后习题作业答案
文章目录 1.8列出文件处理系统和DBMS之间的四个显著区别. 1.9 解释物理数据独立性的概念,以及它在数据库系统中的重要性. 1.10 列出数据库管理系统的五个职责.对每个职责,说明当它不能被履行 ...
- c语言编程一个数的质子求出来,量子力学第一章课外练习题
第一章绪论 一.填空题 1.1923年,德布洛意提出物质波概念,认为任何实物粒子,如电子.质子等,也具有波动性,对于质量为1克,速度为1米/秒的粒子,其德布洛意波长为0.123A(保留三位有效数字). ...
- 数据结构——从概念到c++实现(王红梅第3版)第一章算法设计题答案
第一章 1.找出整型数组A[n]中的最大值和次大值. #include<iostream> using namespace std; int main() {int max,second_ ...
最新文章
- 京东和小米正在使用AI取代人工客服 | 海斌访谈
- Python 爬虫 - Instagram异步协程
- 软件构建之链接应用--链接脚本
- 如何给Typora安装主题
- Android万年历课程设计,电子万年历的设计(课程设计)
- 【C++学习详细教程目录】
- 1.How Models work
- 1247 排排站 USACO(查分+hash)
- syntaxnet python调用
- ECharts属性设置
- linux 行尾加字符串,linux – cat in expect脚本在字符串结尾添加新行
- java报505_Java调用URL错误,报505
- jqGrid获取数据库数据的方式
- 注册测绘师20180301-测绘基准
- mysql emoji表情_mysql utf8mb4与emoji表情
- swift中swiftNotice的pleaseWait()方法
- CT计算机组成及其特点,浅析CT图像的特点及常用扫描方式
- 转:CWnd的函数,以后可以在这儿找了!
- 长篇故事| 世上的感情真的需要门当户对吗?
- 如何利用支付宝实现异地、跨行转账0元手续费