I found this answer on the site and it does not compile, does anyone know why? H
ID: 3635441 • Letter: I
Question
I found this answer on the site and it does not compile, does anyone know why? Here is a copy of the code:
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
int score;
};
float Average(student *, int number);
void SortTestScores(student *, int number);
int main()
{
struct student *scores, *temp;
float averageScore =0;
int number,i;
cout<<"Enter number of test scores";
cin>> number;
scores= new student[number];
temp=scores;
cout<<"Enter test scores: "<<endl;
for(i=0; i<number; i++)
{
cout<<"Enter name and score: ";
cin>>temp->name;
cin>>temp->score;
temp++;
}
SortTestScores(scores, number);
cout<<"Sorted test scores: "<<endl;
temp= scores;
for(i=0; i<number; i++)
{
cout<<temp->name<<" "<<temp->score<<endl;
temp++;
}
averageScore= Average(scores, number);
cout<<"Average test score is: "<<averageScore<<endl;
return 0;
}
Explanation / Answer
The VS2010 compiler gives unresolved externals error, because functions are not defined. Try this code. here I defined average function, and sorting function using insertion sort. Use step-by-step debugging in VS to see how it works.
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
int score;
};
float Average(student *scoreA, int number)
{
float result = 0;
for (int i = 0; i < number; i++)
result += scoreA[i].score;
return (result/number);
}
void SortTestScores(student *scoreA, int number)
{
student key;
int j;
for (int i = 1; i < number; i++)
{
key = scoreA[i];
j = i - 1;
while (j >= 0 && scoreA[j].score > key.score)
{
scoreA[j+1] = scoreA[j];
j--;
}
scoreA[j+1] = key;
}
}
int main()
{
student *scores, *temp;
float averageScore = 0;
int number, i;
cout << "Enter number of test scores";
cin >> number;
scores = new student[number];
temp = scores;
cout<<"Enter test scores: "<<endl;
for(i = 0; i < number; i++)
{
cout<<"Enter name" << i+1 <<": ";
cin>>temp->name;
cout<<"Enter score" << i+1 <<": ";
cin>>temp->score;
temp++;
}
SortTestScores(scores, number);
cout<<"Sorted test scores: "<<endl;
temp = scores;
for(i = 0; i < number; i++)
{
cout<<temp->name<<" "<<temp->score<<endl;
temp++;
}
averageScore = Average(scores, number);
cout<<"Average test score is: "<<averageScore<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.