C++Primer學習筆記+練習答案-第一章
練習答案
Exercise 1.1: Review the documentation for your compiler and determine what file naming convention it uses. Compile and run the main program from page 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.
#include<iostream>
int main(){
return -1;
}
Exercise 1.3: Write a program to print Hello, World on the standard output.
int main(){
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 main(){
std::cout<<"Enter two numbers"<<std::endl;
int v1,v2;
std::cin>>v1>>v2;
std::cout<<"The product of "<<v1<<" and "
<<v2<<" is "<<(v1*v2)<<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(){
std::cout<<"Enter two numbers"<<std::endl;
int v1,v2;
std::cin>>v1>>v2;
std::cout<<"The product of "<<v1<<" and "
<<v2<<" is "<<(v1*v2)<<std::endl;
return 0;
}
Exercise 1.6: Explain whether the following program fragment is legal.
std::cout << "The sum of " << v1;
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
If the program is legal, what does it do? If the program is not legal, why not? How would you fix it?
不合法,可刪除第一第二行的分號或者在這兩行前面加上“std::cout”。 一種修改方式
std::cout << "The sum of " << v1
<< " and " << v2
<< " is " << v1 + v2 << std::endl;
Exercise 1.7: Compile a program that has incorrectly nested comments