I have been writing a program using linked list and just inputing single int's into the list and then averaging them and outputing which inputs where about the average for some reason i can not get the program to calculate or output the above average?
#include <iostream>
usingnamespace std;
struct Data
{
int score;
Data* next;
};
int main()
{
Data* head = 0;
while (true)
{
Data* aData = new Data;
cout << "Please enter your numbers to be averaged[-1 to quit]: ";
cin >> aData->score;
cin.ignore(1000, 10);
//check for sentinel value
if (aData->score == -1) break;
aData->next = head;
head = aData;
}
int count = 0;
int sum = 0;
int nGreater = 0;
Data* p;
for (p = head; p; p = p->next)
{
sum += p->score;
count++;
}
if (count > 0)
{
float average = float(sum) / count;
cout << "The average of " << count << " scores is " << average << endl;
nGreater = (p->score > average);
cout << nGreater << " scores were above the average.";
}
else
cout << "No scores were entered. \n";
while(head)
{
Data* next = head->next;
delete head;
head = next;
}
return 0;
}
#include <iostream>
usingnamespace std;
struct Data
{
int score;
Data* next;
};
int main()
{
Data* head = 0;
while (true)
{
Data* aData = new Data;
cout << "Please enter your numbers to be averaged[-1 to quit]: ";
cin >> aData->score;
cin.ignore(1000, 10);
//check for sentinel value
if (aData->score == -1) break;
aData->next = head;
head = aData;
}
int count = 0;
int sum = 0;
Data* p;
for (p = head; p; p = p->next)
{
sum += p->score;
count++;
}
if (count > 0)
{
float average = float(sum) / count;
cout << "The average of " << count << " scores is " << average << endl;
}
else
cout << "No scores were entered. \n";
int nGreater = 0;
float average;
for (p = head; p; p = p->next)
{
if (p->score > average) nGreater++;
}
cout << nGreater << " scores higher than the average." ;
cout << endl;
while(head)
{
Data* next = head->next;
delete head;
head = next;
}
return 0;
}
The average at line 43 is different than the one at line 50 which should contain garbage value (recall the chapter on scope of variables), one way to make it right is to move the declaration of average to the top of your code and remove the keyword float at line 43