嵌入式开发学习———Linux环境下C语言学习(五)
·
学习打卡
一维整型数组
一维整型数组是C语言中存储相同类型数据(整数)的连续内存空间。其定义格式为:
int array_name[size];
例如:
int numbers[5] = {10, 3, 7, 2, 8};
数组元素通过索引(从0开始)访问,如numbers[0]表示第一个元素。
冒泡排序
冒泡排序通过多次遍历数组,每次比较相邻元素并交换位置,将较大值逐步“冒泡”到数组末尾。
算法实现:
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换相邻元素
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
时间复杂度为$O(n^2)$,适合小规模数据排序。
选择排序
选择排序每次遍历未排序部分,找到最小(或最大)元素,与未排序部分的第一个元素交换位置。
算法实现:
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// 交换找到的最小元素与当前位置元素
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
时间复杂度同样为$O(n^2)$,但交换次数少于冒泡排序。

作业:
- 定义一个有10个元素的数组,终端输入学生成绩,将成绩排序后输出
运行结果: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define LEN 10 int main(int argc, const char *argv[]) { float score[LEN]={0}; int i,j,max_index,temp; printf("请输入学生成绩:\n"); for(i=0;i<LEN;i++) scanf(" %f",&score[i]); putchar(10); printf("当前学生成绩为:\n"); for(i=0;i<LEN;i++) printf("%-5.1f",score[i]); putchar(10); putchar(10); for(i=0;i<LEN-1;i++) { for(j=i+1,max_index=i;j<LEN;j++) { if(score[max_index]<score[j]) max_index=j; } if(max_index!=i) { temp=score[max_index]; score[max_index]=score[i]; score[i]=temp; } } printf("学生成绩由大到小排序为:\n"); for(i=0;i<LEN;i++) printf("%-5.1f",score[i]); putchar(10); return 0; }

- 终端输入一串字符,以'#'结束,统计大写字母、小写字母和数字字符的个数
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int main(int argc, const char *argv[]) { char str1[100]={" "}; int ch=0,num=0,CH=0,other=0,i=0; printf("请输入字符:\n"); while(1) { str1[i]=getchar(); if(str1[i]<='z'&&str1[i]>='a') ch++; else if(str1[i]<='9'&&str1[i]>='0') num++; else if(str1[i]<='Z'&&str1[i]>='A') CH++; else other++; if(str1[i]=='#') break; i++; } printf("大写字母有%d个,小写字母有%d个,数字有%d个,其他字符有%d个。\n",CH,ch,num,other); return 0; }运行结果:

openvela 操作系统专为 AIoT 领域量身定制,以轻量化、标准兼容、安全性和高度可扩展性为核心特点。openvela 以其卓越的技术优势,已成为众多物联网设备和 AI 硬件的技术首选,涵盖了智能手表、运动手环、智能音箱、耳机、智能家居设备以及机器人等多个领域。
更多推荐


所有评论(0)