是volume 1的课后答案,以前从网上下了几个,可是都不是,这个绝对正宗。先给2-1的答案。
2-1
Modify Hello.cpp so that it prints out your name and age (or shoe size, or your dog’s age, if that makes you feel better). Compile and run the program.
Solution:
The original Hello.cpp appeared in the text as follows:
// Saying Hello with C++
#include // Stream declarations
using namespace std;
int main() {
cout << "Hello, World! I am "
<< 8 << " Today!" << endl;
}
Here’s my rewrite:
//: S02:Hello2.cpp
#include
using namespace std;
int main() {
cout << "Hello, World! I am Chuck Allison." << endl;
cout << "I have two dogs:" << endl;
cout << "Sheba, who is " << 5 << ", and" << endl;
cout << "Muffy, who is 8." << endl;
cout << "(I feel much better!)" << endl;
}
/* Output:
Hello, World! I am Chuck Allison.
I have two dogs:
Sheba, who is 5, and
Muffy, who is 8.
(I feel much better!)
*/ ///:~
I chose to have separate statements that send output to cout, but I could have printed everything in a single statement if I had wanted, like the example in the text does. Note that in the case of Sheba’s age, I printed 5 as an integer, but for Muffy I included the numeral in the literal text. In this case it makes no difference, but when you print floating-point numbers that have decimals, you get 6 decimals by default. Bruce discusses later in the text how to control output of floating-point numbers.
1