2014-08-31 170 views
0

我對C++相當陌生,而且我有一個困擾我的時間最長的問題。我必須編寫一個程序,動態分配兩個足夠大的數組,以保存我創建的遊戲中用戶定義的玩家名稱和玩家分數。允許用戶輸入名稱得分對中的得分。對於每個玩過該遊戲的玩家,用戶鍵入一個代表學生姓名的字符串,後面跟一個表示玩家得分的整數。一旦輸入了名稱和相應的評分,數組就應該被傳遞到一個函數中,將數據從最高分到最低分(降序)排序。應該調用另一個函數來計算平均分數。該計劃應顯示從最高得分球員到最低得分球員的球員列表,並將得分平均值與相應標題進行比較。使用指針符號,而不是數組符號儘可能計算陣列平均值的麻煩

這裏是我的代碼:

#include <iostream> 
#include <string> 
#include <iomanip> 
using namespace std; 

void sortPlayers(string[],int[], int); 
void calcAvg(int[], int); 

int main() 
{ 
    int *scores; 
    string *names; 
    int numPlayers, 
    count; 

    cout << "How many players are there?: " << endl; 
    cin >> numPlayers; 

    scores = new int[numPlayers]; 
    names = new string[numPlayers]; 

    for (count = 0; count < numPlayers; count++) 
    { 
     cout << "Enter the name and score of player " << (count + 1)<< ":" << endl; 
     cin >> names[count] >> scores[count]; 

    } 


    sortPlayers(names, scores, numPlayers); 

    cout << "Here is what you entered: " << endl; 
    for (count = 0; count < numPlayers; count++) 
    { 
     cout << names[count]<< " " << scores[count] << endl; 
    } 
    calcAvg(scores, numPlayers); 


    delete [] scores, names; 
    scores = 0; 
    names = 0; 

    return 0; 


} 

void sortPlayers(string names[], int scores[], int numPlayers) 
{ 
    int startScan, maxIndex, maxValue; 
    string tempid; 

    for (startScan = 0; startScan < (numPlayers - 1); startScan++) 
    { 
     maxIndex = startScan; 
     maxValue = scores[startScan]; 
     tempid = names[startScan]; 
     for(int index = startScan + 1; index < numPlayers; index++) 
     { 
      if (scores[index] > maxValue) 
      { 
       maxValue = scores[index]; 
       tempid = names[index]; 
       maxIndex = index; 
       } 
      } 
      scores[maxIndex] = scores[startScan]; 
      names[maxIndex] = names[startScan]; 
      scores[startScan] = maxValue; 
      names[startScan] = tempid; 
     } 
} 

void calcAvg(int scores[], int numPlayers) 
{ 
    int total = 0; 
    double avg = 0; 

    for(int i = 0; i < numPlayers; i++) 

     total += scores[numPlayers]; 

    avg = total/numPlayers; 

    cout << "The average of all the scores is: " << fixed << avg << endl; 
} 

排序部分工作正常,但我有平均正常顯示的麻煩。它每次顯示爲負數(例如-3157838390) 任何人都可以幫我解決這個問題嗎?它與我的指針有什麼關係?

+0

的「這裏是你輸入的內容」行只是進行檢查,看該陣列正常工作... – 2014-08-31 02:55:39

+5

我不能過分強調學習得到[最小的完整的例子]的重要性(http://stackoverflow.com/help/mcve)。 – Beta 2014-08-31 02:59:54

+1

如果您使用調試器,我會在calcAvg函數中放置一個斷點,並查看數組的外觀和總共在做什麼等。 – justanotherdev 2014-08-31 03:01:53

回答

2

在這一行

total += scores[numPlayers]; 

要添加從陣列之外的值。將其更改爲:

total += scores[i]; 
+0

OMG!謝謝你的工作! – 2014-08-31 03:20:08