蓝桥杯嵌入式备赛与复盘
大学参加了2年的蓝桥杯嵌入式,从国优到国三,以后应该再也不会参加了,但还是稍微记录一下吧。
蓝桥杯比赛经历
- 参加深圳大学物光学院蓝桥杯校内赛 → 通过选拔
- 经验:优先排查硬件问题,怀疑开发板有问题就直接申请换板,别死磕怀疑自己浪费时间。
- 本校考场 → 省赛 → 省一
- 哈工深考场 → 国赛 → 心态崩了,没发挥出正常水平 → 国优
- 经验:从易到难先把稳拿分的基础模块写完,一步步推进;早上一定要吃早饭,不然考试中途肚子痛太影响状态(亲身教训)。
蓝桥杯总结
- 熟练使用 STM32 HAL 库配置板载外设,验证驱动正常后再做好模块封装;
- 熟练搭建基于滴答定时器(
uwTick)的伪实时轮询框架,用于多任务调度; - 重点练好串口/字符串数据解析代码;
- 早上进考场前一定要吃饱 🥪。
答题步骤
- 选择题
- 速读程序题要求,理清需要用到哪些外设模块
- 快速搭建工程模板代码
- 细读题目要求
- 先实现 LED、KEY、LCD 基础显示与交互
- 逐个突破题目细节与逻辑模块
注意要点
多个数组共用递增索引时,把
i++单独拆出来写❌ 反面案例:
cValue_A[i++] = Value; Value_B[i++] = Value;1
2✅ 正确写法:
cValue_A[i] = Value; Value_B[i] = Value; i++;1
2
3EEPROM 通过 I2C 写完立刻读时必须加延时
cI2CInit(); i2c_24c02_write(EEROM_String_1, 0x00, 5); HAL_Delay(5); i2c_24c02_read(EEROM_String_2, 0x00, 5);1
2
3
4简易随机数:可以直接用系统时基
uwTick取模生成。数字字符转整型不要直接赋值(
'3'的 ASCII 码是51,不是3)❌ 反面案例:
cchar str[3] = {'1', '2', '3'}; int i = str[2]; // 实际拿到的是 '3' 的 ASCII 码 511
2✅ 正确写法:
cchar str[3] = {'1', '2', '3'}; int i = str[2] - '0'; // 得到整数 31
2注意
uint16_t和uint8_t的数值上限,避免溢出。数据处理尽量紧跟在实时响应逻辑后面,不要拆到延迟很长的独立任务里导致状态滞后。
仔细核对题目文本中的边界条件(
>还是>=、=)。应用层代码尽量写清注释,方便后面查错。
修改
main.c以外的.c/.h文件时记得全局重新编译(Rebuild)。变量清零时记得把相关联的标志位、计数器一起清零。
注意题目要求的参数调节步长,以及 LCD 显示的小数位数。
浮点数不要直接用
==比较,容易因精度误差误判。
C 标准库速查
<stdio.h>
1. int sprintf(char *str, const char *format, ...)
将format中包含的字符串赋值到str指向的字符数组
#include <stdio.h>
#include <math.h>
int main()
{
char str[80];
sprintf(str, "Pi 的值 = %f", M_PI);
puts(str);
return(0);
}2
3
4
5
6
7
8
9
10
11
12
2. int snprintf ( char * str, size_t size, const char * format, ... );
将format中包含的前size个字符串赋值到str指向的字符数组
3. int sscanf(const char *str, const char *format, ...)
- 从字符串读取格式化输入
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int day, year;
char weekday[20], month[20], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year );
printf("%s %d, %d = %s\n", month, day, year, weekday );
return(0);
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- 从不定长字符串中提取整型数据
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "(12,23,34,32,1,32,677)";
int num, count = 0;
char *ptr = str; // 指针用于跟踪解析位置
int offset = 0;
// 跳过开头的 '('
if (*ptr == '(') ptr++;
// 循环提取所有整数
while (sscanf(ptr, "%d%n", &num, &offset) == 1) {
printf("提取到第 %d 个数字:%d\n", ++count, num);
ptr += offset; // 移动指针到已解析的位置
// 跳过逗号或结束符 ')'
if (*ptr == ',' || *ptr == ')') ptr++;
else break; // 遇到非法字符终止
}
printf("共提取 %d 个整数\n", count);
return 0;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<string.h>
1. int memcmp(const void *str1, const void *str2, size_t n)
把 str1 和 str2 的前 n 个字节进行比较。
2. char *strcpy(char *dest, const char *src)
把 src 所指向的字符串复制到 dest。
3. char *strncpy(char *dest, const char *src, size_t n)
把 src 所指向的字符串复制到 dest,最多复制 n 个字符。
4. size_t strlen(const char *str)
计算字符串 str 的长度(不含末尾的 \0)。
5. char *strtok(char *str, const char *delim)
按分隔符 delim 拆分字符串 str。
<math.h>
1. double fabs(double x)
返回 x 的绝对值。
2. double pow(double x, double y)
返回 x 的 y 次幂。
<stdlib.h>
1. int abs(int x)
返回整型 x 的绝对值。
2. int rand(void)
返回一个范围在 0 到 RAND_MAX 之间的伪随机数。
3. void srand(unsigned int seed)
设置 rand() 使用的随机数种子。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 10; i++) {
printf("%d ", rand() % 100);
}
printf("\n");
return 0;
}2
3
4
5
6
7
8
9
10
11
12
13
<time.h>
1. time_t time(time_t *timer)
计算当前日历时间,并编码成 time_t 格式。
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time(NULL);
printf("自 1970-01-01 起的小时数 = %ld\n", seconds/3600);
return(0);
}2
3
4
5
6
7
8
9
10
11
12
STM32CUBEMX
时钟配置
STM32G431RBT6的晶振为24MHz

Led
| 引脚 | GPIO mode | GPIO mode level |
|---|---|---|
| PC8 | GPIO_Output | High |
| PC9 | GPIO_Output | High |
| PC10 | GPIO_Output | High |
| PC11 | GPIO_Output | High |
| PC12 | GPIO_Output | High |
| PC13 | GPIO_Output | High |
| PC14 | GPIO_Output | High |
| PC15 | GPIO_Output | High |
| PD2 | GPIO_Output | Low |
Key
| 引脚 | GPIO mode | GPIO mode level |
|---|---|---|
| PA0 | GPIO_Input | Low |
| PB0 | GPIO_Input | Low |
| PB1 | GPIO_Input | Low |
| PB2 | GPIO_Input | Low |
Adc
ADC1的Mode->Asynchronous clock mode divided by 2
ADC2的Mode->Asynchronous clock mode divided by 2
TIM
模式配置 
参数设置 
开启时钟中断 
RTC

代码日记
main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "rtc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "string.h"
#include "lcd.h"
#include "i2c.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
__IO uint32_t uwTick_LED_Set_Point;
__IO uint32_t uwTick_KEY_Set_Point;
__IO uint32_t uwTick_LCD_Set_Point;
/*LED*/
uint16_t ucLed;
/*KEY*/
uint16_t Key_Val,Key_Down,Key_Up,Key_Old;
/*I2C*/
uint8_t EEROM_String_1[5]={11,22,33,44,55};
uint8_t EEROM_String_2[5]={0};
uint8_t RES_K;
/*LCD*/
uint8_t Lcd_String[21];
//UART
uint8_t Rx_String[10];
uint8_t Rx_Flag;
uint8_t Rx_Buff;
//信号发生器
uint16_t PWM_T_Point;
uint16_t PWM_D_Point;
float PWM_Duty;
//时钟
RTC_TimeTypeDef H_M_S;
RTC_DateTypeDef Y_M_D;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void Led_Proc(void);
void Key_Proc(void);
void Lcd_Proc(void);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_ADC1_Init();
MX_ADC2_Init();
MX_TIM2_Init();
MX_TIM3_Init();
MX_TIM6_Init();
MX_TIM17_Init();
MX_RTC_Init();
/* USER CODE BEGIN 2 */
LCD_Init();
LCD_SetTextColor(White);
LCD_SetBackColor(Black);
LCD_Clear(Black);
I2CInit();
i2c_24c02_write(EEROM_String_1, 0x00, 5);
HAL_Delay(5);
i2c_24c02_read(EEROM_String_2, 0x00, 5);
i2c_4017_write(0x0e);
RES_K = i2c_4017_read();
HAL_UART_Receive_IT(&huart1, (uint8_t*)&Rx_Buff, 1);
HAL_TIM_Base_Start(&htim2);
HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_2);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
Led_Proc();
Key_Proc();
Lcd_Proc();
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3;
RCC_OscInitStruct.PLL.PLLN = 20;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
void Led_Proc(void)
{
if(uwTick-uwTick_LED_Set_Point<100)return;
uwTick_LED_Set_Point=uwTick;
Led_Disp(ucLed);
}
void Key_Proc(void)
{
if(uwTick-uwTick_KEY_Set_Point<50)return;
uwTick_KEY_Set_Point=uwTick;
Key_Val=Key_Scan();
Key_Down=Key_Val&(Key_Val^Key_Old);
Key_Up=~Key_Val&(Key_Val^Key_Old);
Key_Old=Key_Val;
if(Key_Down==1)
{
ucLed=0x01;
}
else if(Key_Down==2)
{
ucLed=0x02;
}
else if(Key_Down==3)
{
ucLed=0x04;
}
else if(Key_Down==4)
{
ucLed=0x08;
}
}
void Lcd_Proc(void)
{
if(uwTick-uwTick_LCD_Set_Point<100)return;
uwTick_LCD_Set_Point=uwTick;
HAL_RTC_GetTime(&hrtc, &H_M_S, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc, &Y_M_D, RTC_FORMAT_BIN);
sprintf((char*)Lcd_String,"Hello");
LCD_DisplayStringLine(Line0,Lcd_String);
sprintf((char*)Lcd_String,"R37:%3.2fV",get_ADC2()*3.3/4096);
LCD_DisplayStringLine(Line1,Lcd_String);
sprintf((char*)Lcd_String,"R38:%3.2fV",get_ADC1()*3.3/4096);
LCD_DisplayStringLine(Line2,Lcd_String);
sprintf((char*)Lcd_String,"ROM:%02d-%02d-%02d-%02d-%02d",EEROM_String_2[0],
EEROM_String_2[1],EEROM_String_2[2],EEROM_String_2[3],EEROM_String_2[4]);
LCD_DisplayStringLine(Line3,Lcd_String);
sprintf((char*)Lcd_String,"RES_K:%d",RES_K);
LCD_DisplayStringLine(Line4,Lcd_String);
sprintf((char*)Lcd_String,"PWM_T:%05d",1000000/PWM_T_Point);
LCD_DisplayStringLine(Line5,Lcd_String);
sprintf((char*)Lcd_String,"PWM_Duty:%4.2f",PWM_Duty*100);
LCD_DisplayStringLine(Line6,Lcd_String);
sprintf((char*)Lcd_String,"Date:%02d-%02d-%02d",Y_M_D.Year,Y_M_D.Month,Y_M_D.Date);
LCD_DisplayStringLine(Line7,Lcd_String);
sprintf((char*)Lcd_String,"Time:%02d-%02d-%02d",H_M_S.Hours,H_M_S.Minutes,H_M_S.Seconds);
LCD_DisplayStringLine(Line8,Lcd_String);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart==&huart1)
{
Rx_String[Rx_Flag++]=Rx_Buff;
if(Rx_String[Rx_Flag-1]==0x0A)
{
HAL_UART_Transmit(&huart1,(uint8_t*)&Rx_String,Rx_Flag,0xFFFF);
while(HAL_UART_GetState(&huart1)==HAL_UART_STATE_BUSY_TX);
memset(Rx_String,0x00,sizeof(Rx_String));
Rx_Flag=0;
}
HAL_UART_Receive_IT(&huart1,(uint8_t*)&Rx_Buff,1);
}
}
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM2)
{
if(htim->Channel==HAL_TIM_ACTIVE_CHANNEL_1)
{
PWM_T_Point = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_1);
PWM_Duty = (float)PWM_D_Point/PWM_T_Point;
}
else if(htim->Channel==HAL_TIM_ACTIVE_CHANNEL_2)
{
PWM_D_Point = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_2);
}
}
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
gpio
/* USER CODE BEGIN 2 */
void Led_Disp(uint8_t ucLed)
{
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2 ,GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_All ,GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOC, ucLed<<8 ,GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2 ,GPIO_PIN_RESET);
return;
}
uint8_t Key_Scan(void)
{
uint8_t ucKey_Val;
if(!HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))ucKey_Val=4;
else if(!HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0))ucKey_Val=1;
else if(!HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1))ucKey_Val=2;
else if(!HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2))ucKey_Val=3;
return ucKey_Val;
}
/* USER CODE END 2 */2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* USER CODE BEGIN Prototypes */
void Led_Disp(uint8_t ucLed);
uint8_t Key_Scan(void);
/* USER CODE END Prototypes */2
3
4
adc
/* USER CODE BEGIN 1 */
float get_ADC1(void)
{
float Voltage;
HAL_ADC_Start(&hadc1);
Voltage=HAL_ADC_GetValue(&hadc1);
HAL_ADC_Stop(&hadc1);
return Voltage;
}
float get_ADC2(void)
{
float Voltage;
HAL_ADC_Start(&hadc2);
Voltage=HAL_ADC_GetValue(&hadc2);
HAL_ADC_Stop(&hadc2);
return Voltage;
}
/* USER CODE END 1 */2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* USER CODE BEGIN Prototypes */
float get_ADC1(void);
float get_ADC2(void);
/* USER CODE END Prototypes */2
3
4
i2c
void i2c_24c02_write(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum)
{
I2CStart();
I2CSendByte(0xA0);
I2CWaitAck();
I2CSendByte(ucAddr);
I2CWaitAck();
while(ucNum--)
{
I2CSendByte(*pucBuf++);
I2CWaitAck();
}
I2CStop();
}
void i2c_24c02_read(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum)
{
I2CStart();
I2CSendByte(0xA0);
I2CWaitAck();
I2CSendByte(ucAddr);
I2CWaitAck();
I2CStart();
I2CSendByte(0xA1);
I2CWaitAck();
while(ucNum--)
{
*pucBuf++ = I2CReceiveByte();
if(ucNum)
I2CSendAck();
else
I2CSendNotAck();
}
I2CStop();
}
void i2c_4017_write(uint8_t RES_K)
{
I2CStart();
I2CSendByte(0x5E);
I2CWaitAck();
I2CSendByte(RES_K);
I2CWaitAck();
I2CStop();
}
uint8_t i2c_4017_read(void)
{
uint8_t RES_K;
I2CStart();
I2CSendByte(0x5F);
I2CWaitAck();
RES_K=I2CReceiveByte();
I2CWaitAck();
I2CStop();
return RES_K;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
void i2c_24c02_write(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum);
void i2c_24c02_read(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum);
void i2c_4017_write(uint8_t RES_K);
uint8_t i2c_4017_read(void);2
3
4
时间差
#include <stdio.h>
#include <time.h>
#include <math.h>
int main() {
struct tm start_tm = {0};
struct tm end_tm = {0};
// 设置起始时间:2023-12-31 23:30
start_tm.tm_year = 2023 - 1900; // 年份从1900年开始计算
start_tm.tm_mon = 12 - 1; // 月份0~11(1月=0)
start_tm.tm_mday = 31;
start_tm.tm_hour = 23;
start_tm.tm_min = 30;
start_tm.tm_isdst = -1; // 自动判断夏令时
// 设置结束时间:2033-01-23 20:10
end_tm.tm_year = 2033 - 1900;
end_tm.tm_mon = 1 - 1; // 1月对应0
end_tm.tm_mday = 23;
end_tm.tm_hour = 20;
end_tm.tm_min = 10;
end_tm.tm_isdst = -1;
// 转换为time_t类型(自动处理闰年、月份溢出等)
time_t start = mktime(&start_tm);
time_t end = mktime(&end_tm);
// 计算时间差
double diff_seconds = difftime(end, start);
double diff_hours = diff_seconds / 3600.0;
printf("时间差:%.2f 小时\n", diff_hours); // 输出保留两位小数
return 0;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35