CPrimer中文版(第4版)习题及详细分析.docVIP

  • 23
  • 0
  • 约5.64万字
  • 约 61页
  • 2017-04-12 发布于四川
  • 举报
CPrimer中文版(第4版)习题及详细分析

习题 1.1 查看所用的编译器文档,了解它所用的文件命名规范。编译并运行本节的main 程序。 【解答】 一般而言,C++编译器要求待编译的程序保存在文件中。C++程序中一般涉及两 类文件:头文件和源文件。大多数系统中,文件的名字由文件名和文件后缀(又 称扩展名)组成。文件后缀通常表明文件的类型,如头文件的后缀可以是.h 或.hpp 等;源文件的后缀可以是.cc 或.cpp 等,具体的后缀与使用的编译器有 关。通常可以通过编译器所提供的联机帮助文档了解其文件命名规范。 习题1.2 修改程序使其返回-1。返回值-1 通常作为程序运行失败的指示器。然而,系统 不同,如何(甚至是否)报告main 函数运行失败也不同。重新编译并再次运行 程序,看看你的系统如何处理main 函数的运行失败指示器。 【解答】 笔者所使用的Windows操作系统并不报告main 函数的运行失败,因此,程序返 回-1 或返回0 在运行效果上没有什么区别。但是,如果在DOS 命令提示符方式 下运行程序,然后再键入echo %ERRORLEVEL%命令,则系统会显示返回值-1。 习题1.3 编一个程序,在标准输出上打印“Hello, World”。 #include iostream #include windows.h using namespace std; int main() { system(CLS); coutHello,World!endl; return 0; } 习题1.4 我们的程序利用内置的加法操作符“+”来产生两个数的和。编写程序,使用乘 法操作符“*”产生两个数的积。 #include iostream #include windows.h using namespace std; int main() { system(CLS); coutEnter two numbers:endl; int v1,v2; cinv1v2; coutThe product of v1 and v2 is v1*v2endl; return 0; } 习题1.5 我们的程序使用了一条较长的输出语句。重写程序,使用单独的语句打印每一 个操作数。 #include iostream #include windows.h using namespace std; int main() { system(CLS); cout Enter two numbers: endl; int v1, v2; cin v1 v2; cout The sum of ; cout v1; cout and ; cout v2; cout is ; cout v1 + v2 ; cout endl; return 0; }习题1.6 解释下面的程序段: std::cout The sum of v1; and v2; is v1 + v2 std::endl; 这段代码合法吗?如果合法,为什么?如果不合法,又为什么? 【解答】 这段代码不合法。 注意,第1、2、4 行的末尾有分号,表示这段代码包含三条语句,即第1、2 行 各为一个语句,第3、4 行构成一个语句。“”为二元操作符,在第2、3 两 条语句中,第一个“”缺少左操作数,因此不合法。 在第2、3 行的开头加上“std::cout”,即可更正。 习题1.7 编译有不正确嵌套注释的程序。 【解答】 由注释对嵌套导致的编译器错误信息通常令人迷惑。例如,在笔者所用的编译 器中编译1.3 节中给出的带有不正确嵌套注释的程序: #include iostream /* * comment pairs /* */ cannot nest. * cannot nest is considered source code, * as is the rest of the program */ int main() { return 0; } 编译器会给出如下错误信息: error C2143: syntax error : missing ; before error C2501: include : missing storage-class or type specifiers warning C4138: */ found outside of comment (第6 行) error C2143: syntax error : missing ; before { (第8 行) error C2447: { : missing function header (old-style formal list?)(第 8 行) 习题1.8 指出下列输出语句哪些(如果有)是

文档评论(0)

1亿VIP精品文档

相关文档