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.
大意:学习一下如何使用你的编译器
赶紧学习一下!
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.
大意:尝试在main函数中返回-1,看看会怎么样
会怎么样,也不会怎么样。这里就是解释了return 0是表示程序运行正常的意思,return -1是表示程序运行错误的意思。一般如果程序运行正常,return 0是可以不写的
1.3 Write a program to print Hello, World on the standard output.
大意:打印你好,世界
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World" << endl;
}
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>
// 注意:这段代码不是我写的,是c++ primer书中给出的
// 但是我们可以来学习一下大师的代码,是怎么样的
int main()
{
// 首先,第一步就非常厉害,用了一个逗号分隔符,同时声明了2个变量
int v1 = 0, v2 = 0;
// 没有使用using namespace,而是使用了std::代替,避免出现重名问题
// 在cin这一步中,使用了一个链式调用,简单便捷
std::cin >> v1 >> v2;
// 由于下面代码太长了,不适合阅读,于是对其进行了分段处理,方便阅读
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
// 由此可见,大师的代码果然让人受益匪浅
}
那么,我们如何来模仿一下呢,毕竟抄代码是非常容易的
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The multiplication of " << v1 << " and " << v2
<< " is " << v1 * v2 << std::endl;
}
由此可见,跟大师学习,你的代码也可以变得非常厉害!
1.5 We wrote the output in one large statement. Rewrite the program to use a separate statement to print each operand.
大意:我们的输出语句太长了,给它写成单独的语句
说实话没太懂,是想说把输出语句拆开吗?那应该不是很难吧
1.6 Explain whether the following program fragment is legal.
// 以下代码为c++ primer书中提供的练习题 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?
大意:看看这段代码正确吗?如何修正呢?
这个代码明显有问题,主要在于第一句末尾添加了分号结束了,因此和第二段连不上了,把第一句末尾的分号去掉就好了(假设我们不考虑前边是否定义过v1和v2的话)。
1.7 Compile a program that has incorrectly nested comments.
大意:编译一个不正确的嵌套注释的程序
这个题目想说多行注释不能嵌套调用,理由也很简单,因为内部的注释的开头会被当成注释,但是内部的注释的结尾会被当成外边的注释的结束
1.8 Indicate which, if any, of the following output statements are legal:
std::cout << "/*"; std::cout << "*/"; std::cout << /* "*/" */; std::cout << /* "*/" /* "/*" */;
After you've predicted what will happen, test your answers by comiling a program with each of these statements. Correct any errors you encounter.
大意:看看这几个语句,哪一个是对的
第一个明显是对的,/*是一个字符串
第二个明显也是对的,*/是一个字符串
第三个肯定不太对,第一个/*是一个注释,到第二个*/结束的时候,把一个引号注释掉了,就剩下了一个引号,这个肯定不对
第四个有点麻烦,第一个/*是一个注释,到第二个*/注释掉了一个引号,然后是一个字符串,到第二个/*都是字符串,然后字符串结束了是一个注释,注释到最后一个*/又注释掉了一个引号。所以说绕了一圈,这个是对的
说句实话,这一看就不像是一个正常人写的出来的代码。。
1.9 Write a program that uses a while to sum the numbers from 50 to 100.
大意:用while循环从50加到100
#include <