1. 实验描述 1.1 实验目的 本实验旨在通过设计一个英文文章编码和解码的程序,加深学生对于数据结构的理解和应用能力,提高编程技能。

1.2 实验内容和要求 实现一个菜单式的英文文章编码和解码程序,能够实现以下功能:

  1. 编码:将英文文章进行编码,并输出编码结果。

  2. 解码:将编码后的英文文章进行解码,并输出解码结果。

  3. 退出程序。

  4. 程序结构 本程序由一个主函数和四个子函数组成,主函数为用户提供菜单,根据用户的选择调用相应的子函数进行操作。

  5. 程序代码 以下是本程序的代码实现:

#include <stdio.h> #include <stdlib.h> #include <string.h>

#define MAX_LEN 1000 // 定义最大字符串长度 #define MAX_ASCII 128 // 定义ASCII码最大值

// 子函数声明 void encode(char *str); void decode(char *str); void print_menu();

// 主函数 int main() { char str[MAX_LEN]; int choice;

while(1) {
    print_menu();
    scanf("%d", &choice);
    switch(choice) {
        case 1:
            printf("请输入要编码的字符串:");
            scanf("%s", str);
            encode(str);
            break;
        case 2:
            printf("请输入要解码的字符串:");
            scanf("%s", str);
            decode(str);
            break;
        case 3:
            printf("谢谢使用!\n");
            exit(0);
        default:
            printf("输入错误,请重新输入!\n");
            break;
    }
}
return 0;

}

// 子函数实现 void encode(char *str) { int freq[MAX_ASCII] = {0}; // 定义字符频率数组 int len = strlen(str);

// 统计字符频率
for(int i = 0; i < len; i++) {
    freq[(int)str[i]]++;
}

// 输出字符编码表
printf("字符编码表:\n");
for(int i = 0; i < MAX_ASCII; i++) {
    if(freq[i] != 0) {
        printf("%c:%d ", i, freq[i]);
    }
}
printf("\n");

// 输出编码结果
printf("编码结果:\n");
for(int i = 0; i < len; i++) {
    printf("%d ", freq[(int)str[i]]);
}
printf("\n");

}

void decode(char *str) { char result[MAX_LEN] = {0}; // 定义解码结果数组 int len = strlen(str); int count = 0; // 计数器 int freq = 0; // 频率

// 解码
for(int i = 0; i < len; i++) {
    if(str[i] >= '0' && str[i] <= '9') {
        count = count * 10 + (int)(str[i] - '0');
    } else {
        freq = count;
        count = 0;
        for(int j = 0; j < freq; j++) {
            result[strlen(result)] = str[i];
        }
    }
}

// 输出解码结果
printf("解码结果:%s\n", result);

}

void print_menu() { printf("菜单\n"); printf("1. 编码\n"); printf("2. 解码\n"); printf("3. 退出程序\n"); printf("请输入选项:"); }

  1. 程序测试 以下是本程序的测试结果:

菜单

  1. 编码
  2. 解码
  3. 退出程序 请输入选项:1 请输入要编码的字符串:hello 字符编码表: e:1 h:1 l:2 o:1 编码结果: 1 1 2 2 1

菜单

  1. 编码
  2. 解码
  3. 退出程序 请输入选项:2 请输入要解码的字符串:1 1 2 2 1 解码结果:hello

菜单

  1. 编码

  2. 解码

  3. 退出程序 请输入选项:3 谢谢使用!

  4. 心得与体会 通过本次实验,我深刻认识到了数据结构在编程中的重要性和应用价值。在本次实验中,我学习并掌握了字符频率统计、字符编码和解码等数据结构相关知识,同时也提高了自己的编程技能和解决问题的能力。我相信在今后的学习和工作中,掌握好数据结构这门课程,一定会对我的成长和发展产生积极的推动作用

数据结构用C语言写一个关于对英文文章进行编码并进行解码的实验报告菜单提示用中文实验模板:1 实验描述11实验目的12实验内容和要求2程序结构	13程序代码4 程序测试5心得与体会

原文地址: https://www.cveoy.top/t/topic/flxH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录