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

自定义比较函数问题:C语言数组最值差判断结果异常求助

C语言数组最值差值判断代码问题排查

核心问题点

  • 函数参数类型不匹配:函数声明alle_gleich(double*, int)和定义alle_gleich(double* array[], int anz)不一致,传入的是double数组,而定义的形参是double指针数组,导致类型不兼容。需将定义的形参改为double* array(数组传参会退化为指针)。
  • 最值变量类型错误:当前用double* max/min存储数组元素的地址,比较的是地址大小而非数值大小,完全偏离需求。应改为直接存储数值:double max = array[0]; double min = array[0];。
  • 逻辑判断与输出反置:需求是差值大于0.001时输出“值不相同”,但当前代码中return 1对应输出“Die Werte sind identisch!”(值相同),逻辑完全相反。需调整判断条件或输出分支。
  • 宏定义拼写错误:_CRT_SECURE_NO_WARINGS拼写错误,正确应为_CRT_SECURE_NO_WARNINGS(少了字母N)。
  • 变量类型不匹配:werte_identisch被定义为double类型,但函数返回的是int类型,需修正为int类型。

修正后的代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int alle_gleich(double*, int);
int pruefe_sort(double*, int);
double max_delta(double*, int);

int alle_gleich(double* array, int anz)
{
    int i = 0;

    if (anz < 2)
        return -1;

    double max = array[0];
    double min = array[0];

    for (; i < anz; i++)
    {
        if (array[i] > max)
            max = array[i];
        if (array[i] < min)
            min = array[i];
    }

    // 差值<=0.001时认为值相同,返回1;否则返回0
    if ((max - min) <= 0.001)
        return 1;
    else
        return 0;
}

int main(void)
{
    int n = 4;
    double werte_praktisch_gleich[] = { 9.9995, 10.0, 10.0002, 9.99991 };
    double werte_sort_0123[] = { 0, 1, 2, 3 };
    double werte_unsortiert[] = { 1, 3, 2, 0 };
    double werte_maxabw_0komma1[] = { 1.0, 1.05, 0.95, 1.01 };
    int werte_identisch;

    werte_identisch = alle_gleich(werte_praktisch_gleich, n);
    
    if (werte_identisch == 1)
        printf("Die Werte sind identisch!\n");
    else
        printf("Die Werte sind nicht identisch!\n");
    
    return 0;
}

内容的提问来源于stack exchange,提问作者Linas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:34:55