C++ Primer 习题 [第一次阅读]
2016-04-01 本文已影响0人
Angsi
第一章
1.3
//1.3
#include <iostream>
using namespace std;
int main() {
std::cout << "Hello, World!" << endl;
return 0;
}
1.4
//1.4
#include <iostream>
using namespace std;
int main() {
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
std::cout << "The mul of " << v1 << " and " << v2
<< " is " << v1 * v2 << std::endl;
return 0;
}
1.5
//1.5
#include <iostream>
using namespace std;
int main() {
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of ";
std::cout << v1;
std::cout << " and ";
std::cout << v2;
std::cout << " is ";
std::cout << v1 + v2;
std::cout << std::endl;
std::cout << "The mul 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:解释下面程序片段是否合法
std::cout << "The sum of " << v1;
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
❓如果程序是合法的,它会输出什么?
The sum of v1
❓如果程序不合法,原因何在?
' ; '代表了程序的一条语句的结束,剩下的语句不知道写入哪一个ostream对象当中
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
❓应该如何修正?
std::cout << "The sum of " << v1;
std::cout << " and " << v2;
std::cout << " is " << v1 + v2 << std::endl;
1.3节练习
1.7 编译一个包含不正确的嵌套注释的程序,观察编译器返回的错误信息
代码
#include <iostream>
using namespace std;
/*
* 注释对/* */不能嵌套
* "不能嵌套"几个字会被认为是源码
* 像剩余程序一样处理
*/
int main() {
return 0;
}
错误信息:
main.cpp:7:13: warning: '/*' within block comment [-Wcomment]
* 注释对/* */不能嵌套
^
main.cpp:7:18: error: unknown type name '不能嵌套'
* 注释对/* */不能嵌套
^
main.cpp:8:4: error: expected unqualified-id
* "不能嵌套"几个字会被认为是源码
^
1 warning and 2 errors generated.
make[3]: *** [CMakeFiles/C___Primer.dir/main.cpp.o] Error 1
make[2]: *** [CMakeFiles/C___Primer.dir/all] Error 2
make[1]: *** [CMakeFiles/C___Primer.dir/rule] Error 2
make: *** [C___Primer] Error 2
1.8 指出下列哪些输出语句是合法的(如果有的话):
std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;
std::cout << /* "*/" /* "/*" */;
预测编译这些语句会产生什么样的结果,实际编译这些语句来验证你的答案(编写一个小程序,每次将上述一条语句作为其主体),改正每个编译错误
std::cout << "/*"; 输出:/*
std::cout << "*/"; 输出:*/
std::cout << /* "*/" */; 报错
std::cout << /* "*/" /* "/*" */; 输出:/*
报错信息 及 代码
错误代码:
std::cout << /* "*/" */;
报错信息:
main.cpp:8:24: warning: missing terminating '"' character [-Winvalid-pp-token]
std::cout << /* "*/" */;
^
main.cpp:8:24: error: expected expression
1 warning and 1 error generated.
更正代码
std::cout << /* "*/" */"; 输出*/