阵列的长度长于所需的时间

  • 本文关键字:时间 于所需 阵列 c
  • 更新时间 :
  • 英文 :


在以下程序中,

    int * accepted_ids = (int *) malloc(sizeof(int)*N);
    double * accepted_scores = (double *)malloc(sizeof(double)*N);
    int * unaccepted_ids = (int *) malloc(sizeof(int)*N);
    double * unaccepted_scores = (double *) malloc(sizeof(double)*N);

这些内存分配正在为每个内存的大小 N创建数组,即使所需元素的数量远低于 N

由于程序使用了一个随机数生成器,因此我们无法事先分辨它们每一个都需要多少内存。

如何解决这个困境?

(最多5分(
单个维数阵列分数存储的分数 他们在高中获得的大学候选人。元素索引 阵列的ID是这些候选人的ID。大学接受 平均得分更大或相等的候选人的申请 到4.0。

编写一个将显示的简短程序:

•具有其ID号和平均得分的公认候选人列表。 •未接受的候选人列表,其ID号及其 平均分 •被接受和未接受的候选人的数量。•结果排序 按顺序

应计算平均分数 从范围< 2,6>使用随机数生成器。总数 候选人应作为命令行参数传递给程序。 使您的程序明智地对错误的参数输入。

不允许使用结构。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
// This function tests whether it is possible 
// to convert a string into integer or not.
//
// This function is needed to check the 
// input argument otherwise if you type 
//      C:>myapp.exe abc
// your program will crash.
int is_integer(const char * s)
{
    char * endptr;
    int radix = 10;//decimal number system
    // try to convert s to integer
    strtol(s, &endptr, radix);
    errno = 0;
    // if this conditions are fullfilled,
    // that means, s can't be converted 
    // to an integer.
    if (endptr == s || *endptr != '')
    {
        // argument must be an integer value        
        return 0; // failure
    }
    if (errno == ERANGE)
    {
        // int argument out of range        
        return 0; // failure
    }
    return 1; //success
}
// This function is needed to convert
// a string to an integer value.
int string_to_integer(const char * s)
{
    char * endptr;
    int radix = 10;//decimal number system
    // convert s to integer
    return strtol(s, &endptr, radix);
}
// Generte a random number between M and N.
//
// This function is needed coz rand() can 
// generate only integer values.
double round_between_m_to_n(double M, double N)
{
    return M + (rand() / (RAND_MAX / (N - M)));
}
// This is Bubble sort algorithm
// This is implemented as a user-defined function, 
// coz, you have to use this twice.
// First for accepted scores, 
// then for unaccepted scores.
void sort(int * ids, double * scores, int count)
{
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (scores[i] < scores[j])
            {
                // Swap scores
                double temp = scores[i];
                scores[i] = scores[j];
                scores[j] = temp;
                // Swap ids
                int temp2 = ids[i];
                ids[i] = ids[j];
                ids[j] = temp2;
            }
        }
    }
}
// This function is to print ids and scores
// as a table.
// This is implemented as a user-defined function, 
// coz, you have to use this twice.
// First for accepted scores, 
// then for unaccepted scores.
void print(int * ids, double * scores, int count)
{
    printf("idtavg_scoren");
    printf("-------------------n");
    for (int i = 0; i < count; i++)
    {
        printf("%it%.1fn", ids[i], scores[i]);
    }
}
int main(int argc, char ** argv)
{
    // Program can proceed only if 
    // the # of arguments is exactly 2. 
    // The 1st arg is always app-name.
    if (argc != 2)
    {
        printf("insufficient argumentn");
        return EXIT_FAILURE;
    }
    int N = 0;
    int accepted_scores_count = 0;
    int unaccepted_scores_count = 0;
    double acceptance_threshhold = 4.0;
    if (!is_integer(argv[1]))
    {
        printf("incorrect argument typen");
        return EXIT_FAILURE;
    }
    else
    {
        N = string_to_integer(argv[1]);
        printf("Total %d studentsn", N);
    }
    // Pair of variables are needed to
    // keep track of student-ids.
    // Otherwise, you can't tell what id a 
    // student has when data are sorted.
    int * accepted_ids = (int *)malloc(sizeof(int)*N);
    double * accepted_scores = (double *)malloc(sizeof(double)*N);
    int * unaccepted_ids = (int *)malloc(sizeof(int)*N);
    double * unaccepted_scores = (double *)malloc(sizeof(double)*N);
    //Initialize random seed.
    //If you don't use this, rand() will generate
    //same values each time you run the program.
    srand(time(NULL));
    // Simultaneously generate scores, ids, and
    // store them is sepaerate arrays.
    for (int i = 0; i < N; i++)
    {
        int id = i;
        double score = round_between_m_to_n(2, 6);
        // if the score is greater than or
        // equal to 4.0...
        if (score >= acceptance_threshhold)
        {
            accepted_ids[accepted_scores_count] = i;
            accepted_scores[accepted_scores_count] = score;
            accepted_scores_count++;
        }
        // ... otherwise they are unaccepted.
        else
        {
            unaccepted_ids[unaccepted_scores_count] = i;
            unaccepted_scores[unaccepted_scores_count] = score;
            unaccepted_scores_count++;
        }
    }
    // sort accepted students
    sort(accepted_ids, accepted_scores, accepted_scores_count);
    // sort unaccpeted students
    sort(unaccepted_ids, unaccepted_scores, unaccepted_scores_count);
    // print accepted students
    printf("naccepted  studentsn");
    print(accepted_ids, accepted_scores, accepted_scores_count);
    // print unaccepted students
    printf("nunaccepted  studentsn");
    print(unaccepted_ids, unaccepted_scores, unaccepted_scores_count);
    printf("nEnd of program.n");
    free(accepted_ids);
    free(accepted_scores);
    free(unaccepted_ids);
    free(unaccepted_scores);

    return EXIT_SUCCESS;
}

,因为您知道要生成的数据的学生数量,因此可以使用 all 学生的数据数组:

    int * all_ids = (int *)malloc(sizeof(int)*N);
    double * all_scores = (double *)malloc(sizeof(int)*N);

然后按正常生成数据,保持计数,但将数据分配到all_*数组中:

    for (int i = 0; i < N; i++)
    {
        int id = i;
        double score = round_between_m_to_n(2, 6);
        all_ids[i] = id;
        all_scores[i] = score;
        // if the score is greater than or
        // equal to 4.0...
        if (score >= acceptance_threshhold)
        {
            accepted_scores_count++;
        }
        // ... otherwise they are unaccepted.
        else
        {
            unaccepted_scores_count++;
        }
    }

因为您知道区分被接受学生的阈值,所以您可以稍后将其分开。

现在,您拥有所有数据,以及被接受和不接受的学生人数。使用此信息,您可以为被接受和未接受的学生分配阵列:

    int * accepted_ids = (int *)malloc(sizeof(int) * accepted_scores_count);
    double * accepted_scores = (double *)malloc(sizeof(double) * accepted_scores_count);
    int * unaccepted_ids = (int *)malloc(sizeof(int) * unaccepted_scores_count);
    double * unaccepted_scores = (double *)malloc(sizeof(double) * unaccepted_scores_count);

使用for循环(除了完成数据生成(,将数据分类为被接受的和未经认可的数组

    for (int i = 0, j = 0; (i+j) < N;)
    {
        int id = all_ids[i+j];
        double score = all_scores[i+j];
        // if the score is greater than or
        // equal to 4.0...
        if (score >= acceptance_threshhold)
        {
            accepted_ids[i] = id;
            accepted_scores[i] = score;
            i++;
        }
        // ... otherwise they are unaccepted.
        else
        {
            unaccepted_ids[j] = id;
            unaccepted_scores[j] = score;
            j++;
        }
    }

之后,您继续按普通分类并打印数据。您也必须记住也可以释放all_*数组。

如果您想最终分配更少的内存,则使用realloc。首先要重新限制0个项目,然后每次需要分配更多内容时,使用Realloc分配更多内存。由于Realloc将"复制"现有数据,因此您只能以实际需要的内存。请记住,Realloc并不是一个很好的功能,应该小心地使用它,因为误会非常容易(确保您检查返回值,并在覆盖指针之前跟踪以前的分配(。

相关内容

最新更新