练习1.3
编写程序,在标准输出上打印 Hello, World。
#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 number:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The product 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
解释下面程序片段是否合法。
不合法。输出运算符(<<)左侧的运算对象要是一个iostream对象,这里第一行最后有分号结束了这一句,第二行的(<<)左边没有iostream对象。
改正:去掉第一行最后的分号。
练习1.8
指出下列哪些输出语句是合法的(如果有的话):
std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;
std::cout << /* "*/" /* "/*" */;
输入编译器后,编译器的提示,这里编译器提示的第四行的std下有红线,是因为上一句错误,导致编译器认为上一行语句还没结束
第三行不合法语句应该修改成
std::cout << /* "*/" */"; //在最后加一个引号
修改后,四条语句输出的结果是
std::cout << "/*"; // 输出 '/*'
std::cout << "*/"; // 输出 '*/'
std::cout << /* "*/" */"; // 输出 ' */'
std::cout << /* "*/" /* "/*" */; // 输出 ' /* '
练习1. 9
编写程序,使用while循环将50到100的整数相加。
#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
除了++运算符将运算对象的值增加1之外,还有一个递减运算符(–)实现将值减少1。编写程序,使用递减运算符在循环中按递减顺序打印出10到0之间的整数。
#include <iostream>
int main()
{
int val = 10;
while (val >=0)
{
std::cout << val << std::endl;
--val;
}
return 0;
}
练习1.11
编写程序,提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数。
在打印这两个数所指定的范围内的所有整数之前,先比较两个数的大小,并把小的数赋给small,大的赋给big。
#include <iostream>
int main()
{
int small = 0, big = 0;
std::cout << "Please enter two integers:";
std::cin >> small >> big;
if (small > big) {
int tmp = small;
small = big;
big = tmp;
}
while (small <= big) {
std::cout << small << " ";
++small;
}
std::cout << std::endl;
return 0;
}
练习1.12
下面的for循环完成了什么功能?sum的终值是多少?
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
这个for循环的作用是求-100到100的和,sum的终值是0。
练习1.13
使用for循环重做1.4.1节中的所有练习(第11页)。
练习1.9的for循环版
#include <iostream>
int main()
{
int sum = 0;
for (int i = 50; i <= 100; ++i)
sum += i;
std::cout << "the sum is: " << sum << std::endl;
return 0;
}
练习1.10的for循环版
#include <iostream>
int main()
{
for (int i = 10; i >= 0; --i)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
练习1.11的for循环版
#include <iostream>
int main()
{
int small = 0, big = 0;
std::cout << "Please enter two integers:";
std::cin >> small >> big;
if (small > big) {
int tmp = small;
small = big;
big = tmp;
}
for (int i = small; i <= big; ++i)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
练习1.14
对比for循环和while循环,两种形式的优缺点各是什么?
while的优点和缺点:
- 循环控制变量的初始化在while语句之前,循环控制变量的改变在while循环体中
- 比较适用于不知道具体循环次数的情况
for的优点和缺点:
- 形式简洁,循环控制变量的初始化和修改都放在语句头部分
- 比较适用于已知循环次数的情况
练习1.16
编写程序,从cin读取一组数,输出其和。
#include <iostream>
int main()
{
int num,sum = 0;
while ( std::cin >> num )
{
sum += num;
}
std::cout << sum << std::endl;
return 0;
}
练习1.17
如果输入的所有值都是相等的,本节的程序会输出什么?如果没有重复值,输出又会是怎样的?
如果输出的所有值全都是相等的,会打印出输入值的次数。
如果没有重复的值,在回车单击时打印上一个数出现一次。
练习1.20
在网站http://www.informit.com/title/032174113 上,第1章的代码目录包含了头文件 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
</string></iostream>
这是下载下来的Sales_item.h文件的代码,直接把文件拷贝进你自己的工作目录中,使用时在代码中包含该头文件即可。
#include <iostream>
#include "../include/Sales_item.h"
int main()
{
Sales_item item;
while (std::cin >> item)
{
std::cout << item << std::endl;
}
return 0;
}
练习1.21
编写程序,读取两个 ISBN 相同的 Sales_item 对象,输出他们的和。
#include <iostream>
#include "../include/Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn()) {
std::cout << item1 + item2 << std::endl;
return 0;
}
else {
std::cerr << "Data must refer to same ISBN." << std::endl;
return -1;
}
}
练习1.22
编写程序,读取多个具有相同 ISBN 的销售记录,输出所有记录的和。
#include <iostream>
#include "../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;
}
}
std::cout << total << std::endl;
}
else {
std::cerr << "No data?!" << std::endl;
return -1;
}
return 0;
}
练习1.23
编写程序,读取多条销售记录,并统计每个 ISBN(每本书)有几条销售记录。
#include <iostream>
#include "../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 << " occurs " << cnt << " times " << std::endl;
currItem = valItem;
cnt = 1;
}
}
std::cout << currItem << " occurs " << cnt << " times " << std::endl;
}
return 0;
}