2011-10-06 95 views
1

我一直在試圖自我教自己如何編寫代碼,但是這個練習題難度很大!任何幫助將不勝感激。我已經完成了代碼和邏輯,但只有一個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的第一個分數會被跳過。任何幫助將不勝感激。

回答

0

更改此

if (prev == id) 

要這樣:

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

Btw:countcounter,counterr - >這樣命名變量肯定會丟失你的頭髮

0

這樣做的方法是創建一個map<int, vector<int> >存儲庫,並閱讀學生的ID。一旦你有了這個ID,你可以將他的分數附加到適當的矢量(repository[ID].push_back(score))。

下一步是在map每個項目迭代(基本上在每ID),並計算在陣列中的最大和最小位置(簡單),然後迭代它和總結一切下這兩個位置不是,然後通過repository[ID].length分(小心不要除以0!)

0

你所描述的是從代碼中預期的。當id改變時(prev != id)它不會執行if (prev == id)部分的塊中的代碼,因此不會更新像highlow這樣的變量。我認爲,無論prev是否等於id,都有一段代碼需要執行。特別是檢查新的高分或低分,但也許是在那裏的一切?