您的位置:首页 > 编程语言 > C语言/C++

C++程序设计(第三版)谭浩强 一章习题

2017-05-10 21:55 295 查看
作者:叁念

1.请根据你的了解,叙述c++的特点。c++对c有哪些发展?

1.1 特点:相对于C语言来讲,C语言是结构化和模块化的语言,它是基于过程的。而C++是面向对象的语言,一切事物皆是对象,它即可用于基于过程的结构化程序,又可用于面向对象的程序设计。另外对象有它的属性,面向对象的基本特点是封装,继承,和多态。

1.2 c++在c+的发展主要表现在两个方面:

在原来基于过程的机制基础上,对c语言的功能做了不少的扩充

增加了面向对象的机制

2.一个c++程序是由哪几部分构成的?其中每一部分起什么作用?

构成及其作用:

1、预处理命令:每个程序都开头一堆#include,#define符号,#pragma编译开关

2、全局声明部分:类型声明和全局变量,用于全局声明类、结构、枚举的定义,也可以设置全局变量

3、函数:即程序执行的具体过程、顺序、逻辑定义(如下所示简单程序)

#include <iostream>
using namespace std;
int main()
{
cout<<"HelloWord";
return 0;
}


3.从接到一个任务到得到最终结果,一般要经过几个步骤?

1.用c++编写程序(源程序 .cpp)

2.对源程序进行编译(目标程序 .obj)

3.将目标文件连接(可执行二进制文件 .exe)

4.运行程序

5.分析运行结果

4.请说明编辑,编译,连接的作用。在编译后得到的目标文件为什么不能直接运行?

1.编辑:编写代码的过程

2.编译:对源程序进行词法检查和语法检查。编译后可得到 .obj 目标文件

3.连接:使用系统提供的“连接程序linker”将目标文件以及系统的库文件或其他信息连接起来,最终形成一个可执行的二进制文件 .exe

5.分析下面程序运行的结果:

#include <iostream>
using namespace std;
int main()
{
cout << "This " << "is ";
cout << "a " << "C++ ";
cout << "program." << endl;
return 0;
}


答案:This is a C++ program.

6.分析下面程序运行的结果:

#include <iostream>
using namespace std;
int main()
{
int a, b, c;
a = 10;
b = 23;
c = a + b;
cout << "a+b=";
cout << c;
cout << endl;
return 0;
}


答案:a+b=33

7.分析下面程序运行的结果:

a8b2

#include <iostream>
using namespace std;
int main()
{
int a, b, c;
int f(int x,int y,int z);
cin >> a >> b >> c;
c = f(a, b, c);
cout << c << endl;
return 0;
}
int f(int x, int y, int z)
{
int m;
if (x < y) m = x;
else m = y;
if (z < m) m = z;
return (m);
}


例:输入4 5 6 输出4

8.改错

#include <iostream>
using namespace std;
int main(); //不加;
{
int a, b;   //a,b没有赋值初始化
c = a + b;  //c没有声明
cout >> "a + b =">>a + b;   // >>改为<<
return 0;
}


正确结果:

#include <iostream>
using namespace std;
int main()
{
int a = 0,b = 0, c;
c = a + b;
cout << "a + b = "<<a + b;
getchar();
return 0;
}


9.改错

#include <iostream>
using namespace std;
int main()
{
int a, b;   //a,b未赋值初始化
c = add(a, b)   //c未声明,语句末尾加 ;号
cout << "a + b = " << c << endl;
return 0;
}
int add(int x, int y);//函数未声明
{
z = x + y;//z未声明
return (z);
}


正确结果:

#include <iostream>
using namespace std;
int add(int x, int y);
int main()
{
int a=0, b=0, c;
c = add(a, b);
cout << "a + b = " << c << endl;
return 0;
}
int add(int x, int y)
{   int z;
z = x + y;
return (z);
}


10.分析程序:从小到大排列,例输入10 6 3 输出 3 6 10

#include <iostream>
using namespace std;
int main()
{
void sort(int x,int y,int z);
int x, y, z;
cin >> x >> y >> z;
sort(x, y, z);
return 0;
}
void sort(int x, int y, int z)
{
int temp;
if (x > y) {
temp = x; x = y; y = temp;
}
if (z < x) cout << z << ',' << x << ',' << y << endl;
else if (z<y) cout << x << ',' << z << ',' << y << endl;
else cout << x << ',' << y << ',' << z << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: