学习c++需要掌握:c语言知识,oop知识以及泛型编程知识
c语言和Pascal:结构化编程
c++和SmallTalk:面向对象编程
C语言:自顶向下的编程,将分支限制为一小组行为良好的结构
OOP:自底向上的编程,从低级组织(类)到高级组织(程序),
泛型编程:对语言惊醒扩展,以便可以只编写一个泛型
第二章
对于某些程序,要让窗口一直打开,知道您按任何键,必须添加 cin.get()
在运行c++程序时,通常从main()
函数开始执行
iostream
中的io指的时输入和输出。C++中的输入/输出方案涉及iostream文件中的多个定义。
头文件cmath
支持各种C语言数学函数
头文件命名约定:
1.c++旧式风格:以.h
结尾
2.c旧式风格:以.h
结尾
3.c++新式风格:没有扩展名
4.转换后的c:加上前缀c,没有扩展名
名称空间支持是一项C++特性
为什么要声明变量
声明通常指出了要存储的数据类型和程序对存储在这里的数据使用的名称。
程序中的声明语句叫做定义声明语句,简称定义。还有引用声明。
对于c++,尽可能在首次使用变量前声明它。
赋值语句
符号=
叫做赋值运算符,赋值运算符可以连续使用,赋值将从右往左进行。
C++语句
声明语句,赋值语句,消息语句,函数调用,函数原型,返回语句
第二章复习题
1.C++程序的模块叫什么?
函数
2.下面的预处理器编译指令是做什么用的?
#include
这将导致在最终编译之前,使用iostream文件的内容替换该编译指令
3.下面的语句是做什么用的?
using namespace std;
它使得程序可以使用std名称空间中的定义
10.定义函数时,在什么情况下不必使用关键字return?
当函数的返回类型为void时,不用在函数中使用return。然而,如果不提供返回值,则可以使用:return ;
11.假设您编写的 main()函数包含如下代码:cout<“Please enter your PIN:”;
而编译器指出cout是一个未知标识符。导致这种问题的原因很可能是什么?指出3种修复这种问题的方法。
cout定义在std命名空间内,而上述代码没有指明命名空间std。
解决办法:1)usingnamespace std;2)using std::cout;3)std::cout<<”Please enter your PIN:”;
编程题
5.摄氏度转华氏度(转换公式:华=1.8*摄+32.0)
#include <iostream> //预处理器编译指令
using namespace std;
int main() {
double H, S; //H为华氏度,S为摄氏度
cout << "Please enter a Celsius value:";
cin >> S;
H = 1.8 * S + 32;
cout << S << " degrees Celsius is " << H << " degrees Fahrenheit.";
return 0;
}
6.光年转换天文单位(转换公式:1光年=63240天文单位)
#include <iostream> //预处理器编译指令
using namespace std;
double convert(double);
int main() {
double distance, year; //year表示光年,distance表示天文单位
cout << "Enter the numer of light years: ";
cin >> year;
distance = convert(year);
cout << year << " light years = " << distance << " astronomical units";
return 0;
}
double convert(double year) {
double distance;
distance = year * 63240;
return distance;
}
7.打印时间
#include <iostream> //预处理器编译指令
using namespace std;
void print(int, int);
int main() {
int hour, minute;
cout << "Enter the numer of hours: ";
cin >> hour;
cout << "Enter the numer of minutes: ";
cin >> minute;
print(hour, minute);
return 0;
}
void print(int hour,int minute) {
cout << "Time: " << hour << ":" << minute;
}