C++程序设计 第一章

第一章 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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若遇浅香kk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值