练习1.1:查用你使用的编译器的文档,确定它使用的命名约定。编译并运行第2页的main程序。
在Ubuntu下面使用命令行执行时,使用g++ main.cpp进行编译后,会得到a.out执行文件,可以用ls指令查看,然后使用./a.out来进行执行。
在windows下面,使用vs来进行编译。
练习1.2:改写程序,让它返回-1。返回值-1通常被当作程序错误的标识。重新编译并运行你的程序,观察你的系统如何处理main返回的错误标识。
Windows7操作系统并不处理或报告程序返回的错误标识,直观上,返回-1的程序与返回0的程序在执行效果上并无不同。但环境变量ERRORLEVEL记录了上一个程序的返回值。因此,在控制台窗口执行修改后的程序,接着执行echo %ERRORLEVEL%,会输出-1.在Linux系统中,执行echo $?有类似效果。
练习1.3:编写程序,在标准输出上打印Hello, World。
#include <iostream>
int main()
{
std::cout << "Hello, World" << std::endl;
return 0;
}
//Hello, World
练习1.4:我们的程序使用加法运算符+来将两个数相加。编写程序使用惩罚运算符*,来打印两个数的积。
#include <iostream>
int main(void)
{
std::cout << "请输入两个数: " << std::endl;
int v1, v2;
std::cin >> v1 >> v2;
std::cout << v1 << "和" << v2 << "的积为: " << v1 * v2 << std::endl;
return 0;
}
//请输入两个数:
//10 20
//10和20的积为 : 200
练习1.5:我们将所有输出放在一条很长的语句中。重写程序,将每个运算对象的打印操作放在一条独立的语句中。
#include <iostream>
int main(void)
{
std::cout << "请输入两个数: ";
std::cout << std::endl;
int v1, v2;
std::cin >> v1 >> v2;
std::cout << v1 << "和" << v2 << "的积为: "
<< v1 * v2 << std::endl;
return 0;
}
//请输入两个数:
//12 15
//12和15的积为 : 180
练习1.6:解释下面的程序片段是否合法。
std::cout << "The sum of " << v1; << "and " << v2; << " is " << v1+v2 << std::endl;
这段代码不合法。前两行末尾有分号,此时这段代码已经结束。第2、3行为两条新的语句。而这两条语句在"<<"前缺少了输出流,应在"<<"之前加上"std::cout"。
正确的代码为:
std::cout << "The sum of " << v1;
std::cout << "and " << v2;
std::cout << " is " << v1+v2 << std::endl;
练习1.7:编译一个包含不正确的嵌套注释的程序,观察编译器返回的错误信息。
#include <iostream>
/*
* 注释对/* */不能嵌套
* “不能嵌套”几个字会被认为是源码,像剩余程序一样处理
* /
int main(void)
{
return 0;
}
按住ctrl+K+C将注释进行重新注释,进行编译。
#include <iostream>
///*
//* 注释对/* */不能嵌套
//* “不能嵌套”几个字会被认为是源码,像剩余程序一样处理
//* /
int main(void)
{
return 0;
}
//C:\Users\liqiang\source\repos\Project1\Debug\Project1.exe(进程 41032)已退出,返回代码为: 0。
// 若要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
// 按任意键关闭此窗口...
练习1.8:指出下列哪些输出语句是合法的(如果有的话)。
std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;
std::cout << /* "*/" /* "/*" */;
预测编译这些语句会产生什么样的结果,实际编译这些语句来验证你的答案(编写一个小程序,每次将上述一条语句作为其主体),改正每个编译错误。
第一条和第二条语句显然是合法的。
#include <iostream>
int main(void)
{
std::cout << "/*";
}
// /*
#include <iostream>
int main(void)
{
std::cout << "*/";
}
// */
#include <iostream>
int main(void)
{
std::cout << /* "*/" */;
}
#include <iostream>
int main(void)
{
std::cout << /* "*/" /* "/*" */;
}
// /*
练习1.9:编写程序,使用while循环将50到100的整数相加。
#include <iostream>
int main()
{
int sum = 0, i = 50;
while (i <= 100)
{
sum += i;
++i;
}
std::cout << "50到100的整数和为50+51+52+53+...+99+100 = " << sum << std::endl;
return 0;
}
//50到100的整数和为50+51+52+53+...+99+100 = 3825
练习1.10:除了++运算符将运算对象的值增加1以外,还有一个递减运算符(--)实现将值减少1。编写程序,使用递减运算符在循环中按递减序打印出10到0之间的整数。
#include <iostream>
int main()
{
int i = 10;
while (i >= 0) {
std::cout << i << " ";
i--;
}
std::cout << std::endl;
return 0;
}
//10 9 8 7 6 5 4 3 2 1 0
#include <iostream>
int main()
{
int i = 11;
while (i > 0)
std::cout << " "<<--i ;
return 0;
}
//10 9 8 7 6 5 4 3 2 1 0
练习1.11:编写程序,提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数。
#include <iostream>
int main()
{
std::cout << "请输入两个整数";
std::cout << std::endl;
int v1, v2;
std::cin >> v1 >> v2;
if (v1 > v2)//由大到小打印
{
while (v1 >= v2)
{
std::cout << v1 << " ";
v1--;
}
}
else //由小到大打印
while (v1 <= v2) {
std::cout << v1 << " ";
v1++;
}
std::cout << std::endl;
return 0;
}
//请输入两个整数
//10 20
//10 11 12 13 14 15 16 17 18 19 20
//请输入两个整数
//25 10
//25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10
//请输入两个整数
//25 25
//25
练习1.12:下面的for循环完成了什么功能?sum的终值是多少?
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
#include <iostream>
int main(void)
{
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
std::cout <<"sum = "<< sum ;
return 0;
}
//sum = 0
练习1.13:使用for循环重做1.4.1节中的所有练习(第11页)。
1.9:
#include <iostream>
int main()
{
int sum = 0, i = 50;
for (int i = 50; i <= 100; i++)
sum += i;
std::cout << "50到100的整数和为50+51+52+53+...+99+100 = "
<< sum << std::endl;
return 0;
}
//50到100的整数和为50+51+52+53+...+99+100 = 3825
1.10:
#include <iostream>
int main()
{
int i = 10;
for(int i = 10;i >= 0;i--)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
//10 9 8 7 6 5 4 3 2 1 0
1.11:
#include <iostream>
int main()
{
std::cout << "请输入两个整数";
std::cout << std::endl;
int v1, v2;
std::cin >> v1 >> v2;
if (v1 > v2)//由大到小打印
for (;v1 >= v2; v1--)
std::cout << v1 << " ";
else //由小到大打印
for (; v1 <= v2; v1++)
std::cout << v1 << " ";
std::cout << std::endl;
return 0;
}
//请输入两个整数
//10 20
//10 11 12 13 14 15 16 17 18 19 20
//请输入两个整数
//25 10
//25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10
//请输入两个整数
//25 25
//25
练习1.14:对比for循环和while循环,两种形式的优缺点各是什么?
在循环次数已知的情况下,for循环的形式显然更为简洁。
而循环次数无法预知时,用while循环实现更适合。用特定条件控制循环是否执行,循环体中执行的语句可能导致循环判定条件发生变化。
练习1.15:编写程序,包含第14页“再探编译”中讨论的常见错误。熟悉编译器生成的错误信息。
对于复杂程序中的错误,编译器给出的错误信息很可能无法应对到真正的需哦呜位置并给出准确的错误原因。这是很正常的,因为某些时候我们人类都无法准确判断程序员到底犯了什么错误,在当前人工智能技术发展水平下,要求编译器超越人类的智能是不现实的。
练习1.16:编写程序,从cin读取一组数,输出其和。
#include <iostream>
int main()
{
int sum = 0, value = 0;
std::cout << "请输入一些数,按住Ctrl+Z表示结束"
<< std::endl;
for (; std::cin >> value;)
sum += value;
std::cout << "读入的两数之和为:"
<< sum << std::endl;
return 0;
}
//请输入一些数,按住Ctrl + Z表示结束
//10 20 30 40
//^ Z
//读入的两数之和为 : 100
#include <iostream>
int main(void)
{
int sum = 0, value=0;
while (std::cin >> value)
sum += value;
std::cout << "sum = " << sum << std::endl;
return 0;
}
//10 20 30 40 50 ^ Z
//sum = 150
练习1.17:如果输入的所有值都是相等的,本节的程序会输出什么?如果没有重复值,输出又会是怎样的?
#include <iostream>
int main(void)
{
//currVal是我们正在统计的数,我们将读入的新值存入val
int currVal = 0, val = 0;
//读取第一个数,并确保确实有数据可以处理
if (std::cin >> val) {
int cnt = 1; //保存我们正在处理的当前值的个数
while (std::cin >> val) { //读取剩余的数
if (val == currVal) //如果值相同
++cnt; //将cnt+1
else { //否则,打印前一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; //记住新值
cnt = 1; //重置计数器
}
}//while循环在这里结束
//技术打印文件中最后一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
}//最外层的if语句在这里结束
return 0;
}
//
//42 42 42 42 42 55 55 62 100 100
//0 occurs 1 times
//42 occurs 4 times
//55 occurs 2 times
//62 occurs 1 times
#include <iostream>
int main(void)
{
//currVal是我们正在统计的数,我们将读入的新值存入val
int currVal = 0, val = 0;
//读取第一个数,并确保确实有数据可以处理
if (std::cin >> val) {
int cnt = 1; //保存我们正在处理的当前值的个数
while (std::cin >> val) { //读取剩余的数
if (val == currVal) //如果值相同
++cnt; //将cnt+1
else { //否则,打印前一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; //记住新值
cnt = 1; //重置计数器
}
}//while循环在这里结束
//技术打印文件中最后一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
}//最外层的if语句在这里结束
return 0;
}
//100 100 100 100 100 100 100 100
//0 occurs 1 times
练习1.18:编译并运行本节的程序,给它输入全都相等的值。再次运行程序,输入没有重复的值。
#include <iostream>
int main(void)
{
//currVal是我们正在统计的数,我们将读入的新值存入val
int currVal = 0, val = 0;
//读取第一个数,并确保确实有数据可以处理
if (std::cin >> val) {
int cnt = 1; //保存我们正在处理的当前值的个数
while (std::cin >> val) { //读取剩余的数
if (val == currVal) //如果值相同
++cnt; //将cnt+1
else { //否则,打印前一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; //记住新值
cnt = 1; //重置计数器
}
}//while循环在这里结束
//技术打印文件中最后一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
}//最外层的if语句在这里结束
return 0;
}
//10 10 10 10
//0 occurs 1 times
//1 2 3 4 5
//10 occurs 3 times
//1 occurs 1 times
//2 occurs 1 times
//3 occurs 1 times
//4 occurs 1 times
//
练习1.19:修改你为1.4.1节练习1.10(第11页)所编写的程序(打印一个范围内的数),使其能处理用户输入的第一个数比第二个数小的情况。
上面1.10的代码已经包含了上述的功能了。
练习1.20:在网站http://www.informit.com/title/0321714113 上,第1章的代码目录汇总包含了头文件Sales_item.h。将它拷贝到你自己的工作目录中。用它编写一个程序,读取一组书籍销售记录,将每条记录打印到标准输出上。
Sales_item.h
#ifndef SALESITEM_H
#define SALESITEM_H
#include <iostream>
#include <string>
class Sales_item {
public:
Sales_item(const std::string &book) :isbn(book), units_sold(0), revenue(0.0) {}
Sales_item(std::istream &is) { is >> *this; }
friend std::istream& operator>>(std::istream &, Sales_item &);
friend std::ostream& operator<<(std::ostream &, const Sales_item &);
public:
Sales_item & operator+=(const Sales_item&);
public:
double avg_price() const;
bool same_isbn(const Sales_item &rhs)const {
return isbn == rhs.isbn;
}
Sales_item() :units_sold(0), revenue(0.0) {}
public:
std::string isbn;
unsigned units_sold;
double revenue;
};
using std::istream;
using std::ostream;
Sales_item operator+(const Sales_item &, const Sales_item &);
inline bool operator==(const Sales_item &lhs, const Sales_item &rhs) {
return lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue && lhs.same_isbn(rhs);
}
inline bool operator!=(const Sales_item &lhs, const Sales_item &rhs) {
return !(lhs == rhs);
}
inline Sales_item & Sales_item::operator +=(const Sales_item &rhs) {
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
inline Sales_item operator+(const Sales_item &lhs, const Sales_item &rhs) {
Sales_item ret(lhs);
ret += rhs;
return ret;
}
inline istream& operator>>(istream &in, Sales_item &s) {
double price;
in >> s.isbn >> s.units_sold >> price;
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_item();
return in;
}
inline ostream& operator<<(ostream &out, const Sales_item &s) {
out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue << "\t" << s.avg_price();
return out;
}
inline double Sales_item::avg_price() const {
if (units_sold)
return revenue / units_sold;
else
return 0;
}
#endif
main.cpp
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item book;
std::cout << "请输入销售记录:"
<< std::endl;
while (std::cin >> book) {
std::cout << "ISBN、售出本数和平均售价为 "
<< book << std::endl;
}
return 0;
}
//请输入销售记录:
//0 - 201 - 70353 - X 4 24.99
//ISBN、售出本数和平均售价为 0 - 201 - 70353 - X 4 99.96 24.99
练习1.21:编写程序,读取两个ISBN相同的Sales_item对象,输出它们的和。
Sales_item.h
/*
* 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, 561
friend 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 bool
operator==(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;
#else
Sales_item() : units_sold(0), revenue(0.0) { }
#endif
Sales_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 pointer
Sales_item& operator+=(const Sales_item&);
// operations on Sales_item objects
std::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_INITS
unsigned units_sold = 0; // explicitly initialized
double revenue = 0.0;
#else
unsigned 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_item
return 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 return
ret += 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 succeeded
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_item(); // input failed: reset object to default state
return 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;
else
return 0;
}
#endif
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item trans1, trans2;
std::cout << "请输入两条ISBN相同的销售记录:"
<< std::endl;
std::cin >> trans1 >> trans2;
if (compareIsbn(trans1, trans2))
std::cout << "汇总信息:ISBN、售出本数、销售额和平均售价为 " << trans1 + trans2 << std::endl;
else
std::cout << "两条销售记录的ISBN不同" << std::endl;
return 0;
}
//请输入两条ISBN相同的销售记录:
//0 - 201 - 70353 - X 3 20.00 0 - 201 - 70353 - X 2 25.00
//汇总信息:ISBN、售出本数、销售额和平均售价为 0 0 0
这里为什么结果不对我也不清楚。
练习1.22:编写程序,读取多个具有相同ISBN的销售记录,输出所有记录的和。
#include <iostream>
#include "Sales_item.h"
int main(void)
{
Sales_item total, trans;
std::cout << "请输入几条ISBN相同的销售记录:" << std::endl;
if (std::cin >> total)
{
while (std::cin >> trans)
if (compareIsbn(total, trans))//ISBN相同
total += trans;
else//ISBN不同
{
std::cout << "ISBN不同" << std::endl;
return -1;
}
std::cout << "汇总信息:ISBN、售出本数、销售额和平均售价为 "
<< total << std::endl;
}
else
{
std::cout << "没有数据" << std::endl;
return -1;
}
return 0;
}
//请输入几条ISBN相同的销售记录:
//0 - 201 - 70353 - X 3 20.00 0 - 201 - 70353 - X 3 20.00 0 - 201 - 70353 - X 3 20.00 0 - 201 - 70353 - X 3 20.00
//没有数据
练习1.23:编写程序,读取多条销售记录,并统计每个ISBN(每本书)有几条销售记录。
#include <iostream>
#include "Sales_item.h"
int main() {
Sales_item item;
Sales_item curItem;
if (std::cin >> curItem)
{
int cnt = 1;
while (std::cin >> item)
{
if (curItem.isbn() == item.isbn())
{
cnt += 1;
}
else
{
std::cout << curItem.isbn() << " has " << cnt << " records." << std::endl;
curItem = item;
cnt = 1;
}
}
std::cout << curItem.isbn() << " has " << cnt << " records." << std::endl;
}
return 0;
}
//0 - 201 - 7033 - X 4 20.00
//0 - 201 - 7033 - X 3 20.00
//
//0 - 201 - 7032 - X 4 20.00
//0 - 201 - 7033 - X has 2 records.
//
//^Z
//0 - 201 - 7032 - X has 1 records.
练习1.24:输入表示多个ISBN的多条销售记录来测试上一个程序,每个ISBN的记录应该聚在一起。
和练习1.23一样。
练习1.25:借助网站上的Sales_item.h头文件,编译并运行本节给出的书店程序。
#include<iostream>
#include "Sales_item.h" //自定义头文件,定义Sale_itemd的类,此处省略
using namespace std;
int main()
{
Sales_item total; //保存下一条交易记录的变量
//读入第一条记录,确保有数据可以处理
if (std::cin >> total) {
Sales_item trans;//保存和的变量
//读入并处理剩余交易记录
// 如果我们仍在处理相同的书
while (cin >> trans) {
if (total.isbn() == trans.isbn())
total += trans;//更新销售总额
else {
//打印前一本书的结果
std::cout << total << std::endl;
total = trans; //total现在表示下一本书的销售信息
}
}
std::cout << total << endl;//打印最后一本不同的书的结果
}else {
//没有输入,警告读者!
std::cerr << "No data?!" << std::endl;
return -1;//表示失败
}
return 0;
}
//0 - 201 - 7033 - X 4 20.00
//No data ? !