第一章的习题答案
Exercise 1.1: Review the documentation for your compiler and determine what file naming convention it uses. Compile and run the main program frompage 2.
Exercise 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.
//正常结束的程序返回值(exit value)为 0
//当返回值为 -1 的时候,echo $? 值为 255
//255 意味着返回值超出了指定的范围(0-255)
Ref:Exit Codes With Special Meanings
Exercise 1.3: Write a program to print Hello, World on the standard output.
#include <iostream>
int main(int argc, char const *argv[])
{
std::cout << "Hello, World" << std::endl;
return 0;
}
Exercise 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>
int a,b = 0;
int main(int argc, char const *argv[])
{
std::cout << "Enter two numbers: ";
std::cin >> a >> b;
std::cout << "The result of " <<
a << " multiply with " <<
b << " is " << a*b << std::endl;
return 0;
}
Exercise 1.5: We wrote the output in one large statement. Rewrite the program to use a separate statement to print each operand.
#include <iostream>
int main(int argc, char const *argv[])
{
int a, b = 0;
std::cout << "Enter two numbers: ";
std::cin >> a >> b;
std::cout << "The result of " ;
std::cout << a << " multiply with " << b;
std::cout << " is ";
std::cout << a*b << std::endl;
return 0;
}
Exercise 1.6: Explain whether the following program fragment is legal.
Illegal.
The semicolons at the end of the first and the second line would cause the fragment to finish in advance, leading the rest of the objects in the fragment to have nowhere to place. Deleting the two semicolons would fix the error.
Exercise 1.7: Compile a program that has incorrectly nested comments.
In the book, the author mentioned:
A comment that begins with /* ends with the next */. As a result, one comment pair cannot appear inside another.
/*
* comment pairs /* */ cannot nest.
* ''cannot nest'' is considered source code,
* as is the rest of the program
*/
int main()
{
return 0;
}
errors when compling:
ex_1_7.cpp:4:3: error: empty character constant
* ''cannot nest'' is considered source code,
^~~~~~~~
ex_1_7.cpp:4:16: error: empty character constant
* ''cannot nest'' is considered source code,
Exercise 1.8: Indicate which, if any, of the following output statements are legal:
std::cout << "/*"; // legal, /* treated as a string
std::cout << "*/"; // legal, */ treated as a string
std::cout << /* "*/" */; //illegal, delimiters not pair, leading to miss a quote
std::cout << /* "*/" /* "/*" */; //legal, third delimiter is not paired but quoted, so output would be a string.
After you’ve predicted what will happen, test your answers by compiling a program with each of these statements. Correct any errors you encounter.
Fix for the third segment:
std::cout << /* "*/" */"; //adding a quote at the end of the segment to make it actually output a string.
Exercise 1.9: Write a program that uses a while to sum the numbers from 50 to 100.
#include <iostream>
int main(int argc, char const *argv[])
{
int sum = 0;
int val = 50;
while (val <= 100) {
sum += val;
val++;
}
std::cout << "The result of summation from 50 to 100 is: ";
std::cout << sum;
return 0;
}
Exercise 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.
#include <iostream>
int main(int argc, char const *argv[])
{
int count = 10;
while(count > -1) {
std::cout << count-- << std::endl;
}
return 0;
}
Exercise 1.11: Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
#include <iostream>
int main(int argc, char const *argv[])
{
int small, large = 0;
std::cout << "Specify range by entering two numbers:" << std::endl;
std::cin >> small >> large;
//swap the small val and large val if small val is greater
if(small > large) {
int temp = 0;
temp = small;
small = large;
large = temp;
}
while (small <= large) {
std::cout << large << std::endl;
large --;
}
return 0;
}
Exercise 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;
The for loop is summing the number from -100 to 100. The result is 0.
Exercise 1.13: Rewrite the exercises from § 1.4.1 (p. 13) using for loops.
#include <iostream>
int main(int argc, char const *argv[])
{
//Ex.1.9 rewrite
int sum_19 = 0;
for (int i = 50; i <= 100; ++i) {
sum_19 += i;
}
std::cout << "Ex.1.9 result: " << sum_19 <<std::endl;
//Ex.1.10 rewrite
std::cout << "Ex.1.10 result: " << std::endl;
for(int j = 10; j >= 0; --j) {
std::cout << j << std::endl;
}
//Ex.1.11 rewrite
int small, large = 0;
std::cout << "Enter two numbers to specify the range:" << std::endl;
std::cin >> small >> large;
if(small > large) {
int temp = small;
small = large;
large = temp;
}
for(int i = (large - small); i >= 0; --i) {
std::cout << large-- << std::endl;
}
return 0;
}
Exercise 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?
a good answer for the question:
The main difference between the for's and the while's is a matter of pragmatics: we usually use for when there is a known number of iterations, and use while constructs when the number of iterations in not known in advance. The while vs do … while issue is also of pragmatics, the second executes the instructions once at start, and afterwards it behaves just like the simple while.
Exercise 1.15: Write programs that contain the common errors discussed in the box on page 16. Familiarize yourself with the messages the compiler generates.
#include <iostream>
int main(int argc, char const *argv[])
{
//syntax error
std::cout << "hello world" << std::endl // missing semicolon
std::cout << hello world << std::endl; // missing quote
//type error
int i = "hellworld"; // missmatched type, "helloworld" should be string type
//Declaration error
std::cout << j << std::endl; // val "j" wasn't declared before it is used.
return 0;
}
Exercise 1.16: Write your own version of a program that prints the sum of a set of integers read from 'cin'.
#include <iostream>
int main(int argc, char const *argv[])
{
int sum = 0;
int num = 0;
while (std::cin >> num) {
sum += num;
}
std::cout << "Total: " << sum << std::endl;
return 0;
}
Exercise 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?
* If all the input values are equal, the program will not end until the input reaches the end of the file. It will print the occur times once the program ends.
Exercise 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.
/*The all-equal inputs sequence*/
1
1
1
/*The no repeat inputs sequence*/
1
2
The number 1 occurs: 1 times.
3
The number 2 occurs: 1 times.
4
The number 3 occurs: 1 times.
5
The number 4 occurs: 1 times.
6
The number 5 occurs: 1 times.
Exercise 1.19: Revise the program you wrote for the exercises in § 1.4.1 (p.13) that printed a range of numbers so that it handles input in which the first number is smaller than the second.
See ex.1.11
Exercise 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.
#include <iostream>
#include "Sales_item.h"
int main(int argc, char const *argv[])
{
Sales_item item;
while (std::cin >> item) {
std::cout << item << std::endl;
}
return 0;
}
Exercise 1.21: Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.
#include <iostream>
#include "Sales_item.h"
int main(int argc, char const *argv[])
{
Sales_item item1, item2;
std::cout << "Enter two Sales items: " << std::endl;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn()) {
std::cout << item1 + item2 << std::endl;
return 0;
}
else {
std::cerr << "The two items must have same ISBN" << std::endl;
return -1;
}
}
Exercise 1.22: Write a program that reads several transactions for the same ISBN. Write the sum of all the transactions that were read.
#include <iostream>
#include "Sales_item.h"
int main(int argc, char const *argv[])
{
Sales_item total;
if(std::cin >> total){
Sales_item curritem;
while (std::cin >> curritem) {
if (curritem.isbn() == total.isbn()) {
total += curritem;
}
}
}
std::cout << total << std::endl;
return 0;
}
Exercise 1.23: Write a program that reads several transactions and counts how many transactions occur for each ISBN.
#include <iostream>
#include "Sales_item.h"
int main(int argc, char const *argv[])
{
int totalCnt = 1;
Sales_item item;
if(std::cin >> item) {
Sales_item currItem;
while(std::cin >> currItem) {
if(item.isbn() == currItem.isbn()) {
totalCnt++;
}
else {
std::cout << item.isbn() << " Occurs " << totalCnt << " times." << std::endl;
totalCnt = 1;
item = currItem;
}
}
}
return 0;
}
Exercise 1.24: Test the previous program by giving multiple transactions representing multiple ISBNs. The records for each ISBN should be grouped together.
00-11 5 5.0
00-11 5 5.0
00-22 5 5.0
00-11 Occurs 2 times.
00-33 5 5.0
00-22 Occurs 1 times.
00-44 5 5.0
00-33 Occurs 1 times.
Exercise 1.25: Using the Sales_item.h header from the Web site, compile and execute the bookstore program presented in this section.
/*a couple of same inputs*/
00-11 5 5.0
00-11 5 6.0
00-11 5 7.0
00-11 15 90 6
/*servral different inputs*/
00-11 5 5.0
00-22 5 6.0
00-11 5 25 5
00-33 5 7.0
00-22 5 30 6
00-33 5 35 7
/*no inputs*/
No data?!