首页 > 解决方案 > 返回数组中的最大数

问题描述

typedef struct {int PID;
                int Priority;
                char *Status[8];
                char *Program[20];}Process;

硬编码值

void initTable()
{
    processList[0].PID = 112;
    processList[0].Priority = 1;
    strcpy(processList[0].Status,"Ready");
    strcpy(processList[0].Program,"Alex.txt");
    processList[1].PID = 101;
    processList[1].Priority = 3;
    strcpy(processList[1].Status,"Running");
    strcpy(processList[1].Program,"Alex.txt");
    processList[2].PID = 103;
    processList[2].Priority = 2;
    strcpy(processList[2].Status,"Ready");
    strcpy(processList[2].Program,"Alex.txt");

}

我想返回在这个例子中具有最高优先级值的 i = 1 是最高优先级值

int getNextProcess()
{
    for (int i = 0; i < len; ++i) {
        // return the i with the highest Priority value
    }


    
    return i;
}

标签: c

解决方案


// assuming `Priority` value is never less than 0
// returns -1 if something bad happens
int getNextProcess(Process *processList, int len)
{
    int greatest = -1;
    int greatest_i = -1;
    for (int i = 0; i < len; ++i) {
        if (processList[i].Priority > greatest) {
            greatest = processList[i].Priority;
            greatest_i = i;
    }
}
return greatest_i;
}

推荐阅读