侧边栏壁纸
  • 累计撰写 47 篇文章
  • 累计创建 0 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

第 1 章

1.1

prog1.cc 文件代码:

int main()
{
	return 0;
}

在prog1.cc 文件所在目录下,依次执行下面命令:

➜  Desktop CC prog1.cc
➜  Desktop a.out
➜  Desktop echo $?
0

注:这里prog1.cc 文件所在目录为Desktop;

1.2

prog1.cc 文件代码修改为:

int main()
{
	return -1;
}

在prog1.cc 文件所在目录下,依次执行下面命令:

➜  Desktop CC prog1.cc
➜  Desktop a.out
➜  Desktop echo $?
255

注:这里prog1.cc 文件所在目录为Desktop;

1.3

#include <iostream>

int main() {
    std::cout << "Hello, World" << std::endl;

    return 0;
}

1.4

#include <iostream>

int main() {
    std::cout << "Enter two numbers:" << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The product of " << v1 << " and " << v2
              << " is " << v1 * v2 << std::endl;
    
    return 0;
}

1.5

#include <iostream>

int main() {
    std::cout << "Enter two numbers:";
    std::cout << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The sum of ";
    std::cout << v1;
    std::cout << " and ";
    std::cout << v2;
    std::cout << " is ";
    std::cout << v1 + v2;
    std::cout << std::endl;

    return 0;
}

1.6

std::cout << "The sum of " << v1;
          << " and " << v2;
          << " is " << v1 + v2 << std::endl;

不合法,分号表示一个语句的结束。修正方法:

方法一:

std::cout << "The sum of " << v1;
std::cout << " and " << v2;
std::cout << " is " << v1 + v2 << std::endl;

方法二:

std::cout << "The sum of " << v1
	      << " and " << v2
	      << " is " << v1 + v2 << std::endl;

1.7

#include <iostream>

/*
 * 注释对/* */不能嵌套。
 * "不能嵌套"几个字会被认为是源码,
 * 像剩余程序一样处理
 */
int main() {
    return 0;
}

1.8

std::cout << "/*"; // 合法,输出:/*
std::cout << "*/"; // 合法,输出:*/
std::cout << /* "*/" */; // 不合法
// 编译器提示warning: missing terminating '"' character
// 编译器把第一对/* "*/识别为注释界定符;剩余的" */;识别为源码。
std::cout << /* "*/" /* "/*" */; // 合法,输出 /* 
// 首(/* "*/)尾(/*" */)为界定符;" /* "为源码
// /* "*/" /* "/*" */整个这句的一开始是界定符/*,编译器把和它匹配的最近*/之间的内
// 容( ")识别为注释;接着是",标志着下一个和它匹配的最近"之间的内容( /* )是字符
// 串;接着是界定符/*,编译器把和它匹配的最近*/之间的内容(" )识别为注释。
// 原则:从左往右,就近匹配。

1.9

#include <iostream>

int main() {
    int sum = 0, val = 50;
    while (val <= 100) {
        sum += val;
        ++val;
    }
    std::cout << "Sum of 50 to 100 inclusive is "
              << sum << std::endl;
    
    return 0;
}

1.10

#include <iostream>

int main() {
    int val = 10;
    while (val >= 0) {
        std::cout << val << " ";
        --val;
    }
    std::cout << std::endl;

    return 0;
}

1.11

#include <iostream>

int main() {
    int val1, val2, temp;
    std::cout << "Please input two integers";
    std::cin >> val1 >> val2;
    if (val1 > val2) {
        temp = val1;
        val1 = val2;
        val2 = temp;
    }
    ++val1;
    while (val1 < val2) {
        std::cout << val1 << " ";
        ++val1;
    }
    std::cout << std::endl;

    return 0;
}

1.12

#include <iostream>

int main() {
    int sum = 0;
    // for循环完成-100~+100之间所有整数累加求和
    for (int i = -100; i <= 100; ++i)
        sum += i;
    std::cout << sum << std::endl;

    return 0;
}

sum的终值是0

1.13

#include <iostream>

int main() {
    int sum = 0;
    for (int val = 50; val <= 100; ++val)
        sum += val;
    std::cout << "Sum of 50 to 100 inclusive is "
              << sum << std::endl;

    return 0;
}
#include <iostream>

int main() {
    for (int val = 10; val >= 0; --val)
        std::cout << val << " ";
    std::cout << std::endl;

    return 0;
}
#include <iostream>

int main() {
    int val1, val2, temp;
    std::cout << "Please input two integers";
    std::cin >> val1 >> val2;
    if (val1 > val2) {
        temp = val1;
        val1 = val2;
        val2 = temp;
    }
    for (++val1; val1 < val2; ++val1)
        std::cout << val1 << " ";
    std::cout << std::endl;

    return 0;
}

1.14

while (condition) 
  statement

while 循环的条件判断(condition)语句在每次执行完循环体(statement)语句都会执行,判断是否继续执行循环体。

for (init-statement; condition; expression)
	statement

for 循环的初始化语句(init-statement)在循环开始的时候执行一次,之后执行判断语句(condition),若满足条件,则执行循环体(statement),循环体内的语句执行完后紧接着执行表达式(expression),表达式的作用一般是作用判断语句(condition),使循环在有限次内结束,而不是无限循环。当然 init-statement、conditon和expression这三条语句也可以为空语句(分号不可以省略):

for (;;)
	statement

也可以写多条,多条之间用逗号分隔:

#include <iostream>

int main() {

    for (int i = 0, j = 0; i < 2, j < 2; ++i, ++j)
        std::cout << i << " " << j << '\n';
    std::cout << std::endl;

    return 0;
}

while 循环的优点是书写简单,缺点是程序员可能忘记在循环体(statement)内作用条件判断语句(condition),造成无限循环;for 循环的优点是规范、整洁,不易漏掉作用条件判断(condition)的表达式(expression),缺点是书写稍繁琐。while 循环适合循环次数不确定的情景;for 循环适合循环次数事先已知。

1.15

1.16

#include <iostream>

int main() {
    int sum = 0, value = 0;
    while (std::cin >> value) {
        sum += value;
    }
    std::cout << "Sum is: " << sum << std::endl;

    return 0;
}

1.17

如果输入的值都相等,程序输出相等值的个数;如果没有重复值程序则输出每个数字出现次数为1,按一次Enter,输出上一个数字的统计结果为1.

// 测试数据
3 3 3 3
4
// 运行结果
3 occurs 4 times
// 测试数据
5
// 运行结果
4 occurs 1 times
// 测试数据
6
// 运行结果
5 occurs 1 times
// 测试数据
7
// 运行结果
6 occurs 1 times
// 测试数据
8
// 运行结果
7 occurs 1 times

1.18

// 测试数据
100 100 100 100 100 100
1 2 3 4 5 6 7 8
// 运行结果
100 occurs 6 times
1 occurs 1 times
2 occurs 1 times
3 occurs 1 times
4 occurs 1 times
5 occurs 1 times
6 occurs 1 times
7 occurs 1 times

1.19

1.11 已经考虑到该情况。

1.20

C++ Primer 5th source code download

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
    Sales_item(): units_sold(0), revenue(0.0) { }
    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
    unsigned units_sold;
    double revenue;
};

// 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

main.cpp

#include <iostream>
#include "Sales_item.h"

int main() {
    Sales_item book;
    // 读入 ISBN 号、售出的册数以及销售价格
    std::cin >> book;
    // 写入 ISBN、售出的册数、总销售额和平均价格
    std::cout << book << std::endl;

    return 0;
}

Clion IDE :

// 测试数据
0-201-70353-X 4 24.99

// 运行结果
0-201-70353-X 4 99.96 24.99
  
Process finished with exit code 0

1.21

Sales_item.h 同1.20,main.cpp 内容如下:

#include <iostream>
#include "Sales_item.h"

int main() {
    Sales_item item1, item2;
    std::cin >> item1 >> item2;                 // 读取一对交易记录
    std::cout << item1 + item2 << std::endl;    // 打印它们的和

    return 0;
}

Clion IDE :

// 测试数据
0-201-78345-X 3 20.00
0-201-78456-X 2 25.00

// 运行结果
0-201-78345-X 5 110 22

Process finished with exit code 0

1.22

Sales_item.h 同1.20,main.cpp 内容如下:

/*
 * 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
*/ 

#include <iostream>
#include "Sales_item.h"

int main() 
{
    Sales_item item1, item2;

    std::cin >> item1 >> item2;
	// first check that item1 and item2 represent the same book
	if (item1.isbn() == item2.isbn()) {
    	std::cout << item1 + item2 << std::endl;
    	return 0;   // indicate success
	} else {
    	std::cerr << "Data must refer to same ISBN" 
		          << std::endl;
    	return -1;  // indicate failure
	}
}

Clion IDE :

// 测试数据1
0-201-78345-X 4 20.00
0-201-78345-X 5 20.00
  
// 运行结果1
0-201-78345-X 9 195 21.6667
  
Process finished with exit code 0
  
// 测试数据2
0-202-78222-Y 2 25.00
0-201-78111-X 2 29.00
  
// 运行结果2
Data must refer to same ISBN

Process finished with exit code 255

注:程序结束 0 和 255 正好分别对应 return 0 和 return -1.

1.23

#include <iostream>
#include "Sales_item.h"

int main() {
    Sales_item currItem, valItem;
    if (std::cin >> currItem) {
        int cnt = 1;
        while (std::cin >> valItem) {
            if (valItem.isbn() == currItem.isbn()) {
                ++cnt;
            } else {
                std::cout << currItem.isbn() << " occurs " << cnt << " times " << std::endl;
                currItem = valItem;
                cnt = 1;
            }
        }
        std::cout << currItem.isbn() << " occurs " << cnt << " times " << std::endl;
    }
    return 0;
}
// 测试数据
0-201-78345-X 4 25.0
0-201-78345-X 1 25.0
0-201-78345-X 2 25.0
0-201-78345-X 9 25.0
0-207-78345-X 9 31.0
0-207-78345-X 3 31.0
0-202-78345-X 3 20.0
0-202-78345-X 3 20.0

// 运行结果
0-201-78345-X occurs 4 times 
0-207-78345-X occurs 2 times 
// 接着仍可以继续输入测试数据

1.24

将 exercise_23.cpp 编译运行(代码如 1.23),生成可执行程序。

在控制台执行:

Last login: Wed May 29 08:17:52 on console
➜  ~ /Users/xxx/Desktop/exercise_23  </Users/xxx/Desktop/Untitled-1 >/Users/xxx/Desktop/Untitled-2
➜  ~

Untitled-1 文档内容为:

0-201-78345-X 4 25.0
0-201-78345-X 1 25.0
0-201-78345-X 2 25.0
0-201-78345-X 9 25.0
0-207-78345-X 9 31.0
0-207-78345-X 3 31.0
0-202-78345-X 3 20.0
0-202-78345-X 3 20.0

Untitled-2 文档内容为:

0-201-78345-X occurs 4 times 
0-207-78345-X occurs 2 times 
0-202-78345-X occurs 2 times 

注:该题考查书中知识点使用文件重定向P19P_{19}

1.25

Sales_item.h 同1.20,main.cpp 内容如下:

#include <iostream>
#include "Sales_item.h"

int main() {
    Sales_item total;   // 保存下一条交易记录的变量
    // 读入第一条交易记录,并确保有数据可以处理
    if (std::cin >> total) {
        Sales_item trans;   // 保存和的变量
        // 读入并处理剩余交易记录
        while (std::cin >> trans) {
            // 如果我们仍在处理相同的书
            if (total.isbn() == trans.isbn())
                total += trans;     // 更新总销售额
            else {
                // 打印前一本书的结果
                std::cout << total << std::endl;
                total = trans;      // total 现在表示下一本书的销售额
            }
        }
        std::cout << total << std::endl;    // 打印最后一本书的结果
    } else {
        // 没有输入!警告读者
        std::cerr << "No data?!" << std::endl;
        return -1;  // 表示失败
    }
    return 0;
}
// 测试数据
0-201-78345-X 4 25.0
0-201-78345-X 1 25.0
0-201-78345-X 2 25.0
0-201-78345-X 9 25.0
0-207-78345-X 9 31.0
0-207-78345-X 3 31.0
0-202-78345-X 3 20.0
0-202-78345-X 3 20.0

// 运行结果
0-201-78345-X 16 400 25
0-207-78345-X 12 372 31
32

评论区