使用 C 中的动态内存分配找到一些最小的负数

问题描述 投票:0回答:1

我正在做作业,但有一些无法修复的错误 请你帮助我好吗? 问题是在C中使用动态内存分配 找到最小负元素的某个位置

函数 amnn 是我无法修复的“东西”

非常感谢你

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int nhapmang (int *p,int n)
{
    int i;
    for (i=0;i<n;i++)
    {
        printf ("Nhap vao a[%d] = ",i);
        scanf ("%d",&*(p+i));
    }
}
int inmang (int *p,int n)
{
    for (int i=0;i<n;i++) 
    printf ("   %d",*(p+i));
}

int amnn(int *p, int n)
{
    int tg,tg1;
    for (int i=0;i<n;i++)
    {
        if (*(p+i)<0)
        {
        tg=*(p+i);
        break;
        }
    }
    for (int i=0;i<n;i++)
    {
    if (*(p+i)<0 && (tg>*(p+i)))
        {
        tg1=i;
        }
    }
    printf ("\nvi tri so am nho nhat trong mang la: a[%d]",tg1);
}
int main()
{
    int *p, n,a,amnn1;
    printf ("nhap vao n: ");
    scanf ("%d",&n);
    p=(int*)malloc(n*sizeof(int));
    nhapmang (p,n);
    printf ("\nin ma tran:");
    inmang(p,n);
    amnn(p,n);
return 0;
}

输入:n=5,a[0]=-9,a[1]=5,a[2]=-2,a[3]=-99,a[4]=-99 结果是a[3],a[4]

c dynamic-memory-allocation
1个回答
0
投票

不幸的是,我不明白你的逻辑

amnn

它似乎只处理有一个最小值的情况,因此它不会处理您的样本输入。

我必须完全重构你的代码。注释如下:

#include <stdio.h>
#include <stdlib.h>

// amnn -- find all minimum negative numbers
void
amnn(int *arr,int n)
{

    // number of indexes that contain the minimum value
    int mincount = 0;

    // list of indexes that contain the minimum value
#if ALLOC
    int *idxlist = malloc(sizeof(*idxlist) * n);
#else
    int idxlist[n];
#endif

    // current minimum value
    // start with a positive value to handle initial case
    int minval = 1;

    // loop through all array elements
    for (int curidx = 0;  curidx < n;  ++curidx) {
        int curval = arr[n];

        // we only want negative values
        if (curval >= 0)
            continue;

        // ignore values that are greater than the current minimum
        if (curval > minval)
            continue;

        // we have a new minimum value
        if (curval < minval) {
            // reset count of matching indexes
            mincount = 0;

            // set new minimum value
            minval = curval;
        }

        // current value is part of the set of minimum values
        if (curval == minval)
            idxlist[mincount++] = curidx;
    }

    // print results
    do {
        if (minval >= 0) {
            printf("no negative values found\n");
            break;
        }

        printf("minimum value is: %d\n",minval);

        printf("it is contained in indexes:\n");
        for (int listidx = 0;  listidx < mincount;  ++listidx)
            printf("  %d\n",idxlist[listidx]);
    } while (0);

#if ALLOC
    free(idxlist);
#endif
}
© www.soinside.com 2019 - 2024. All rights reserved.