所以程序收集了一些指定的分數,然後以升序顯示,然後應該是顯示的平均分數。但現在,它只顯示第一個分數,併除以分數的數量。我怎樣才能讓它正確顯示?(C++)函數計算平均回報(第一次得分/得分總數)?
#include <iostream>
#include <iomanip>
using namespace std;
void sortArray(int*, int);
double getAverage(int*, int);
int main()
{
int *scores;
int num_Tests;
cout << "How many test scores would you like to enter?" << endl;
cin >> num_Tests;
scores = new int[num_Tests];
cout << "\nEnter score number (do not use negative numbers):\n";
for (int count = 0; count < num_Tests; count++)
{
cout << count + 1 << ". ";
cin >> scores[count];
}
sortArray(scores, num_Tests);
cout << "\n\n";
cout << "\n\n________________________________________________________________________________" << endl;
cout << "Test Score List (in ascending order)" << endl;
cout << "________________________________________________________________________________" << endl;
for (int count = 0; count < num_Tests; count++)
{
cout << count + 1 << ". ";
cout << scores[count] << endl;
}
cout << "\nAverage test score: " << getAverage(scores, num_Tests) << endl;
return 0;
}
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
double avgScore = 0.0;
ttlScore += *scores;
avgScore = ttlScore/size;
return avgScore;
}
void sortArray(int *scores, int size)
{
int temp;
bool swap;
do
{ swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (scores[count] < scores[count + 1])
{
temp = scores[count];
scores[count] = scores[count + 1];
scores[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
你知道平均值是所有分數除以數字的總和。所以從計算總和開始。 –
你需要遍歷你的分數數組來添加它們,你不能只是做'ttlScore + = *分數',它需要'ttlScore + =分數[index]' –
我可能會提出的另一點是這個代碼可能是如果你在你的main中使用了更多的功能(例如顯示輸出),那麼它就有點整潔。它是個人喜好的問題,但我喜歡我的主要功能:P –