简体   繁体   English

数组中的C ++ max / min元素,不知道数组大小

[英]C++ max/min element in an array without knowing array size

I was given a task, it's nothing special but I did hit the wall here... 我接到了一项任务,这没什么特别的,但我确实在这里撞墙了......

After getting arithmetical means I need to compare them and output the highest and the lowest ones. 获得算术意味着我需要比较它们并输出最高和最低的值。

The x is a student number, the vid[] is the arithmetical mean. x是学号,vid []是算术平均值。

For example: 例如:

Student number x has arithmetical mean vid[i] 学生编号x具有算术平均值vid [i]

and the task wants me to output which student has the highest and which one has the lowest means. 并且任务要求我输出哪个学生最高,哪个学生最低。

The worst part that I can't use stuff like max() and min() because I don't know how many students are there in total. 最糟糕的是我不能使用max()和min()之类的东西,因为我不知道总共有多少学生。 Plus they are all arrays which have the same variable name vid[]. 另外,它们都是具有相同变量名称vid []的数组。

Any help would be appreciated =) 任何帮助将不胜感激=)

int main()
{
    int mokSK=0, p1[25], p2[25], p3[25], x[25], vid[25], iv=0;
    ifstream inFile("inFile.in");
    ofstream outFile("outFile.out");


    inFile >> mokSK;

    for(int i=0;i<mokSK;i++)
    {
        inFile >> x[i] >> p1[i] >> p2[i] >> p3[i];
        vid[i]=(p1[i]+p2[i]+p3[i])/3;
        outFile<< x[i] <<" " << vid[i] << endl;
    }

    return 0;
}

If you want O(1) to access max and min graded students; 如果你想要O(1)访问最大和最小分级的学生; from the beginning of reading, update your max and min graded student in each read pass. 从阅读开始,在每个阅读通行证中更新您的最高和最低分等级学生。

to be more clear: keep track of min and max graded student from the very beginning of the execution and update max and min graded students in each student data reading pass if needed. 更清楚:从执行开始就跟踪最小和最大分级学生,并在需要时更新每个学生数据阅读通行证中的最高和最低分级学生。

int main()
{
  int mokSK=0, p1[25], p2[25], p3[25],x[25],vid[25],iv=0;
  int minmean = INT_MAX; int minstud= 0;// initialize minmean and max mean with first mean
  int maxmean = 0; int maxstud= 0;
  ifstream inFile("inFile.in");
  ofstream outFile("outFile.out");
  inFile >> mokSK;
  for(int i=0;i<mokSK;i++)
  {
    inFile >> x[i] >> p1[i] >> p2[i] >> p3[i];
    vid[i]=(p1[i]+p2[i]+p3[i])/3;
    if(vid[i]>maxmean){maxmean = vid[i]; maxstud = i;}
    if(vid[i]<minmean){minmean = vid[i]; minstud = i;}
    // not handled if multple students have maxmean or minmean
    outFile<< x[i] <<" " << vid[i] << endl; 
  }

 outFile << "Max mean: " << maxmean << ", student id: " << maxstud << endl;
 outFile << "Min mean: " << minmean << ", student id: " << minstud << endl;
 return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM