Basic Prog Prob [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ag开发者_开发问答o.
Improve this questionI've been trying to self-teach myself how to code but this practice problem is a toughie! Any help would be greatly appreciated. I have the code and logic done but there is just one isuee.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ifstream fin;
int id, prev, score, scoree, high = 0, low = 0, total = 0, count = 1, counter = 0, counterr = 0;
double avg = 0;
fin.open("C:\\Users\\E\\Desktop\\Quizzes.dat");
fin >> prev;
fin >> score;
low = score;
high = score;
total = score;
while(!fin.eof())
{
fin >> id;
fin >> scoree; //Problem is that when the ID changes it still inputs a score which gets ignored
if ( counter == counterr && counter != 0 ) //Could of used a BOOL here...
{
high = scoree;
low = scoree;
total = 0;
count = 0;
}
if ( prev == id )
{
if (scoree > high)
{
high = scoree;
}
if (scoree < low)
{
low = scoree;
}
total = total + scoree;
count++;
counter = 0;
}
else
{
total = total - (high+low);
count = count - 2;
avg = total / count;
cout << "ID: " << prev << " " << "AVG: " << avg << endl;
prev = id;
counter++;
counterr++;
}
}
}
The .dat file is just a text file with an ID number and a Score. The idea here is that it reads in a score and id if the ID is the same it checks the scores. The highest and lowest score should be thrown out and the rest averaged. So What my logic is that it adds up all the scores regardless, and only after the ID changes do you subtract the highest and lowest score from total and then - 2 from the count to avg it out. The issue im having is that when I input an ID and its different It also inputs a score and that first score of the new id get skipped. Any help would be greatly appreciated.
Change this
if ( prev == id )
To this:
if ( prev == id || count == 0)
Btw: count
, counter
, counterr
-> naming variables like this is sure recipe for losing your hair
The way to do this is to create a map<int, vector<int> >
repository and you read in the ID of the student. Once you have the ID, you append his score to the appropriate vector (repository[ID].push_back(score)
).
The next step is to iterate over every item in the map
(basically over every ID) and calculate the maximum and minimum positions in the array (trivial) and then iterate over it and sum everything that's not under those two positions, then divide by repository[ID].length
(take care not to divide by 0!)
What you are describing is to be expected from the code. When the id changes (prev != id
) it will not execute the code from the block that goes with the if ( prev == id )
part, and therefore not update variables like high
and low
. I think, regardless of whether prev
equals id
or not, there is some piece of code in that block you always want to execute. Especially checking for new high or low scores, but perhaps everything in there?
精彩评论