C++程序设计(第三版)谭浩强 &&Code
第一章 C++的初步认识
例 1.4 包含类的C++程序
#include<iostream>
using namespace std;
class Student //声明一个类,类名为Student
{
private:
int num;
int score;
public:
void setdata() //定义公用函数setdata
{
cin >> num;
cin >> score;
}
void display()
{
cout << "num=" << num << endl;
cout << "score=" << score << endl;
};
};
Student stud1, stud2, stud3; //定义stud1,stud2和stud3为类的变量,称为对象
int main()
{
stud1. setdata();
stud2. setdata();
stud3. setdata();
stud1. display();
stud2. display();
stud3. display();
}
注:这是一个包含类的最简单的C++程序。原例题是输入输出两个学生的学号和成绩,在此基础上,我把代码改成了输入输出三个学生的学号和成绩。
习题1.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 (y < z) cout << z << " " << x << " " << y << endl;
else if (z < y) cout << x << " " << z << " " << y << endl;
else cout << x << " " << y << " " << z << endl;
}
拓展模块
part 1
//知道一个汉字,获取其ASCII编码,
//需要先把pchar的每个字符转成unsigned char
//直接用int i = pchar[0],得到的是负值
#include <iostream>
using namespace std;
int main()
{
const char * pchar = "烫";
unsigned char ci = pchar[0];
int i = ci;
unsigned char cj = pchar[1];
int j = cj;
cout << pchar << " " << i << "," << j << endl; // 输出204,204 (11001100 11001100)
}
part 2
// 打印ASCII汉字编码表
#include <iostream>
using namespace std;
int main()
{
for (int i = 129; i < 256; ++i) // 129 = 0x81
{
for (int j = 64; j < 256; ++j) // 64 = 0x40
{
char pchar[3];
pchar[0] = i;
pchar[1] = j;
pchar[2] = '\0';
cout << pchar << " " << i << "," << j << " ";
}
}
}
注:此程序为打印所有汉字编码表,慎试用。
part 3
//知道汉字的ASCII码输出汉字
#include <iostream>
using namespace std;
int main()
{
char pchar[3];
pchar[0] = 204;
pchar[1] = 204;
pchar[2] = '\0';
cout << pchar << endl;
}