C++ 学习(1)
个人觉得对程序的学习就是在看懂的基础上,多练习、多调试。因此,本人开始了系统的C++自学旅程。现做如下记录。这些记录主要以程序为主,对个别的函数或细节点不理解的话,多查资料,多看点书。
<span style="font-size:12px;">/程序1.向屏幕打印输出字符串
#include <iostream>//启动预处理器,头文件包含标准输入输出函数
using namespace std;//名称空间,,定义了程序中标识符的作用域。此句把std名称空间中定义的标识符引入当前全局域
int main()//C++中包含一个main函数,返回类型一定是整型
{
cout<<"Hello World!"<<endl;//输出字符Hello World!
cout<<"C++ is better than C.\n";//在C++中有两种输出回车的方式,endl与\n
return 0;//若无此可能会出现警告</span>
<span style="font-size:12px;"> }</span>
个人觉得,打印输出还是比较重要的,在调试程序的时候,经常要判断某些变量的值与设计的是否一致,或与程序阅读者所想的是否一致。比如在观察HEVC中CU等的分割。
<span style="font-size:12px;color:#000000;">//程序2.向屏幕输入两数,求和、平均
#include<iostream>
using namespace std;
int main()
{
int a,b;//定义两个变量为输入做准备
cout<<"Enter two numbers:"<<endl;//提示输入两个数
cin>>a>>b;//从键盘读入数值
cout<<"The sum is:"<<a+b<<endl<<"The average is:"<<(float)(a+b)/2<<endl;//求平均,并输出
return 0;
}</span>
程序2主要展示的就是一种简单的人机交互了,即由用户输入数字,机器求出结果。当前,这段代码有很大的缺陷:只能进行一次。可以通过设置一个用户输入变量来控制程序核心部分的开始与结束,这样就更好了。
<span style="font-size:12px;color:#000000;">程序3.类的使用
#include<iostream>
using namespace std;
class person//创建一个类:关键词class,类名person
{
char name[30];//类中声明了两个私有(默认)成员变量 name 和 age
int age;
public://类成员性质的关键词
void getdata(void);//类中声明了两个公有的成员函数getdata 和 display
void display(void);
};//这个分号不可缺,表明对类声明结束
void person::getdata(void)//类外对成员函数getdata的定义--功能:输入两个参量
{
cout<<"Enter name:\n";
cin>>name;
cout<<"Enter age:"<<endl;
cin>>age;
}
void person::display(void)//类外对成员函数display的定义--功能:显示两个参量
{
cout<<"\nName:"<<name;
cout<<"\nAge:"<<age<<endl;
}
int main()//主函数
{
person p;//创建类person的一个对象p
p.getdata();//对对象p使用点操作符来调用成员函数 getdata 和 display
p.display();
return 0;
}</span>
类是C++的一大特色,对类的掌握极为重要。个人觉得类就相当于一辆汽车的某些部件组成的汽车的某个功能。
下面是参考书中的一些练习的解答。
题目1:写一个程序,从键盘输入一个整数,并在屏幕上显示n行“WELL DONE”字符
解题关键:仿照程序1对字符的打印输出,最为关键的就是使用一种循环来显示n行“WELL DONE”字符
参考程序如下:
<span style="font-size:12px;color:#000000;">#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a number for show rows is:";
cin>>n;
for(int i=n;i>0;i--)//本程序中使用for循环来完成对n行“WELL DONE”字符的显示
cout<<"WELL DONE"<<endl;
return 0;
}</span>
题目2:写一个程序,输入华摄氏度温度值,输出相应的摄氏度温度值。
解题关键:查找华摄氏度温度值与摄氏度温度值转换的公式。
参考程序如下:
<span style="font-size:12px;">#include<iostream>
using namespace std;
class temp
{
int option;
float F,C;
public:
void getdata();
void transform();
void show();
};
void temp::getdata()
{
//根据输入情况自动选择温度单位的转换
cout<<"Enter the Fahrenheit press 1,enter the Centigrade press 2:";
cin>>option;
if(option == 1)
{
cout<<"Enter the Fahrenheit is:";
cin>>F;
}
else if(option==2)
{
cout<<"Enter the Centigrade is:";
cin>>C;
}
else
{
cout<<"Enter the wrong number!"<<endl;
}
}
void temp::transform()
{
if(option==1)
C=(F-32)/1.8;
else if(option==2)
F=C*1.8+32;
}
void temp::show()
{
if(option == 1)
cout<<"The centigrade is:"<<C<<endl;
else if(option == 2)
cout<<"The fahrenheit is:"<<F<<endl;
}
int main()
{
temp p;
p.getdata();
p.transform();
p.show();
return 0;
}</span>
上述参考程序进行了大面积的改进。1.为了理解类的使用,本参考程序声明了一个类“temp”;2.为了实现更好的人机交互,本参考程序设置了变量“option”让用户选择何种温度值的转换。
上述为C++学习的第一课,感觉自已的收获还是满满的。