因此,程序会收集指定的分数,然后按升序显示,然后应显示平均分数。但是现在,它只显示第一个分数,并除以分数。如何才能正确显示?
#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);
}
答案 0 :(得分:0)
getAverage逻辑不正确。您只是添加第一个号码。添加如下:
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
double avgScore = 0.0;
for(int i=0;i<size;i++)
{
ttlScore += *(scores+i);
}
avgScore = ttlScore / size;
return avgScore;
}
答案 1 :(得分:0)
你需要遍历你的得分数组来添加它们,你不能只做ttlScore += *scores
,它必须是ttlScore += scores[index]
示例:
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
for (int i = 0; i < size; i++)
{
ttlScore += scores[i];
}
return ttlScore / size;
}
答案 2 :(得分:0)
*得分引用数组的开头。您需要将指向的数组的所有值相加:
for (int i=0; i < size; i++)
{
ttlScore += scores[i];
}
avgScore = ttlScore / size;
return avgScore;
答案 3 :(得分:0)
我认为这些会对你有帮助,
double getAverage(int * scores,int size){
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
sum += scores[i];
}
avg = (double)sum / size;
return avg;
}
尝试让我知道是否有任何问题?
答案 4 :(得分:0)
我是编程新手,但这就是我所拥有的。
//average function
double average(int* pnData)
{
double result;
int sum = 0; //declare and initialize our variables
int count = 0;
for (int i = 0; i < pnData[i]; i++)
{
sum += pnData[i]; //sum = sum + elements of our array
count++; //increment count
}//end of for loop
result = sum/(double)count;
return result;
}//end of function average
这样您就不必知道数组的长度或数量了。