You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现各城市气温最值计算时函数输出一致问题求助

问题根因
  • 传参错误:每个城市的5个温度存储在以temps + i * 5为起始地址的连续内存中,但你调用getMinMax时始终传入temps(整个温度数组的首地址,对应第一个城市的温度起始位置),函数永远只会计算前5个温度的最值,因此输出结果固定不变。
  • 其他可优化点:main函数标准返回值为int,原代码未释放malloc申请的内存,存在内存泄漏风险。
修正后代码
#include <stdio.h>
#include <stdlib.h>

void getMinMax(int *t)
{
    int i = 0, min = 0, max = 0;
    min = max = *t;

    for(i = 0; i < 5; i++)
    {
        if(min > *(t + i))
        {
            min = *(t + i);
        }
        if(max < *(t + i))
        {
            max = *(t + i);
        }
    }
    printf("Min: %d\nMax: %d\n", min, max);
}   

int main()
{
    char *city[5];
    int *temps, i = 0, j = 0;

    for(i = 0; i < 5; i++)
    {
        city[i] = (char*)malloc(50);
    }
    temps = (int*)malloc(25 * sizeof(int));

    for(i = 0; i < 5; i++)
    {
        printf("Enter city: ");
        scanf("%s", city[i]);
        printf("Yearly temperatures of city %d:\n", i + 1);

        for(j = i * 5; j < (i * 5) + 5; j++)
        {
            scanf("%d",temps + j);
        }
        // 传入当前城市温度的起始地址
        getMinMax(temps + i * 5);
    }

    // 释放申请的内存
    for(i = 0; i < 5; i++)
    {
        free(city[i]);
    }
    free(temps);
    return 0;
}

内容的提问来源于stack exchange,提问作者Hiếu Vi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 06:24:03