Basic Prog Prob

问题描述:

我一直在试图自我教自己如何编写代码,但是这个练习题难度很大!任何帮助将不胜感激。我已经完成了代码和逻辑,但只有一个isuee。Basic Prog Prob

#include <iostream> 
#include <fstream> 

using namespace std; 

void main() 
{ 
    ifstream fin; 
    int id, prev, score, scoree, high = 0, low = 0, total = 0, count = 1, counter = 0, counterr = 0; 
    double avg = 0; 
    fin.open("C:\\Users\\E\\Desktop\\Quizzes.dat"); 
fin >> prev; 
fin >> score; 
low = score; 
high = score; 
total = score; 

while(!fin.eof()) 
{ 
     fin >> id; 
     fin >> scoree; //Problem is that when the ID changes it still inputs a score which gets ignored 

     if (counter == counterr && counter != 0) //Could of used a BOOL here... 
     { 
      high = scoree; 
      low = scoree; 
      total = 0; 
      count = 0; 
     } 

     if (prev == id) 
     {    
      if (scoree > high) 
      { 
       high = scoree; 
      } 
      if (scoree < low) 
      { 
       low = scoree; 
      } 

      total = total + scoree; 
      count++; 
      counter = 0; 

     } 
     else 
     { 
      total = total - (high+low); 
      count = count - 2; 

      avg = total/count; 

      cout << "ID: " << prev << " " << "AVG: " << avg << endl; 

      prev = id; 
      counter++; 
      counterr++; 

     } 
    } 
} 

.dat文件只是一个带有ID号和Score的文本文件。这里的想法是,如果ID与检查分数相同,则它读入分数和ID。应该抛出最高分和最低分,其余的平均分。所以,我的逻辑是它将所有分数相加,无论如何,只有在ID变化之后,您才会从总数中减去最高和最低分数,然后从计数中减去-2以平均分数。我的问题是,当我输入一个ID和它的不同它也会输入一个分数,新ID的第一个分数会被跳过。任何帮助将不胜感激。

更改此

if (prev == id) 

要这样:

if (prev == id || count == 0) 

Btw:countcounter,counterr - >这样命名变量肯定会丢失你的头发

这样做的方法是创建一个map<int, vector<int> >存储库,并阅读学生的ID。一旦你有了这个ID,你可以将他的分数附加到适当的矢量(repository[ID].push_back(score))。

下一步是在map每个项目迭代(基本上在每ID),并计算在阵列中的最大和最小位置(简单),然后迭代它和总结一切下这两个位置不是,然后通过repository[ID].length分(小心不要除以0!)

你所描述的是从代码中预期的。当id改变时(prev != id)它不会执行if (prev == id)部分的块中的代码,因此不会更新像highlow这样的变量。我认为,无论prev是否等于id,都有一段代码需要执行。特别是检查新的高分或低分,但也许是在那里的一切?