三维数组C程序优化:显示重复最高/最低温度的对应时间
问题分析与解决方案
原程序存在两个核心问题:
- 仅记录了最后一个最值对应的时间点,无法展示所有重复的最值记录
- 最大值计算时错误遍历了全年52周,而非用户指定的单周
以下是修复后的代码,同时实现了重复最值的全量展示:
#include <stdio.h> #include <stdlib.h> #include <math.h> // 定义浮点数比较的精度阈值,避免浮点误差导致的判断错误 #define EPSILON 1e-6 void week_statistics(double array[52][7][24], int kalenderwoche) { // 转换为数组索引:第n周对应索引n-1(数组从0开始) int target_week = kalenderwoche - 1; if (target_week < 0 || target_week >= 52) { printf("无效的日历周,请输入1-52之间的数值\n"); return; } // 第一步:遍历指定周,找到最小值和最大值 double min_temp = array[target_week][0][0]; double max_temp = array[target_week][0][0]; for (int j = 0; j < 7; j++) { for (int k = 0; k < 24; k++) { double current = array[target_week][j][k]; if (current < min_temp) { min_temp = current; } if (current > max_temp) { max_temp = current; } } } // 第二步:输出最小值及所有对应时间点 printf("第%d日历周的最低温度为%.2lf°,出现时间:\n", kalenderwoche, min_temp); for (int j = 0; j < 7; j++) { for (int k = 0; k < 24; k++) { // 浮点数比较需用精度阈值判断相等 if (fabs(array[target_week][j][k] - min_temp) < EPSILON) { printf(" 第%d周,%d点\n", j + 1, k + 1); } } } // 第三步:输出最大值及所有对应时间点 printf("\n第%d日历周的最高温度为%.2lf°,出现时间:\n", kalenderwoche, max_temp); for (int j = 0; j < 7; j++) { for (int k = 0; k < 24; k++) { if (fabs(array[target_week][j][k] - max_temp) < EPSILON) { printf(" 第%d周,%d点\n", j + 1, k + 1); } } } } int main() { double array[52][7][24] = {{ {9.6,9.4,9.3,9.1,7.9,7.7,7.3,7.2,8.8,9.3,9.7,9.4,10.2,9.7,9.9,9.5,9.2,9.3,9.2,7.1,6.1,5.9,5.6,5.2}, {4.9,4.6,4.6,4.1,3.5,3.1,2.6,2.6,3.5,5.1,6.2,8.3,9.0,9.3,9.1,8.0,6.8,6.4,5.4,5.2,4.8,4.5,5.0,5.5}, {6.3,6.8,7.0,7.2,7.1,7.2,7.1,7.4,7.7,8.2,8.7,9.1,8.8,8.7,8.6,8.4,8.0,7.9,7.7,7.6,7.5,7.3,7.3,7.2}, {7.1,7.0,6.9,6.8,6.7,6.7,6.7,6.6,6.7,6.8,6.9,7.2,7.5,7.7,8.1,8.3,8.0,7.7,8.1,8.2,7.7,7.5,7.7,7.9}, {8.1,8.0,7.9,7.8,7.5,7.2,6.9,7.2,8.0,8.4,8.7,9.0,8.7,8.9,9.0,7.8,8.5,8.1,7.7,7.7,6.7,7.0,6.5,7.1}, {6.4,6.6,6.3,5.8,5.0,4.9,4.7,4.6,4.9,5.3,6.1,5.5,5.3,5.7,5.8,6.5,6.6,5.8,5.8,7.1,7.0,7.0,6.3,5.8}, {4.4,4.0,3.8,3.8,4.2,4.2,4.3,3.8,4.4,5.2,5.7,5.9,6.1,6.7,6.3,5.9,5.5,5.1,5.0,5.0,5.2,5.7,7.2,7.7} }}; int kalenderwoche = 45; week_statistics(array, kalenderwoche); return 0; }
关键修改点说明
- 修正周索引逻辑:将输入的日历周转换为数组索引(
kalenderwoche-1),确保只处理指定周的数据 - 分两步遍历:先遍历一次找到最值,再遍历一次收集所有符合条件的时间点,解决重复值无法展示的问题
- 浮点精度处理:用
EPSILON阈值结合fabs判断浮点数相等,避免因浮点存储误差导致的漏判 - 简化函数参数:移除不必要的循环变量参数,函数内部自行定义,避免未初始化变量的问题
- 优化输出格式:将所有重复的最值时间点统一列出,更清晰直观
内容的提问来源于stack exchange,提问作者check1_07
相关产品推荐
相关产品推荐

