I'm working on a program that, given a list of values (double
s) from an input file, sorts them in ascending order and calculates the mode
, and print the result in an output file. This is what I came up with so far.
What it should do is assign the mode to the x
th element of the vector, the one that produces the greater value for current
, but when I run this program the mode is always equal to the last element of the vector.
I just can't figure out what mistake I'm doing, because in my mind it seems perfectly logical.
Any help is greatly appreciated.
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("inp.txt");
if(!iFile)
{
cout << "Error input!" << endl;
return -1;
}
ofstream oFile("out.txt");
if(!oFile)
{
cout << "Error output!" << endl;
return -1;
}
double data;
vector<double> list;
while(iFile >> data)
{
list.push_back(data); //put the elements in a vector
sort(list.begin(), list.end()); //and sort them in ascending order
}
for(int m = 0; m < list.size(); ++m) //this is just
{ //to verify
oFile << list[m] << endl; //that the elements
} //are listed in order
int current = 0;
int previous = 0;
int mode = 0;
for(int x = 0; x < list.size(); ++x) //select an element of the vector
{
for(int y = 0; y < list.size(); ++y) //match it against all the other elements of the vector
{
if(list[x] == list[y]) //if they're of equal value
{
++current; //add 1 to variable "current"
}
}
if(current > previous) //if "current" > "previous"
{
mode = list[x]; //set the element "x" (from the first for) of the vector "list" to be the new mode
current = previous; //and set current to be the new previous
}
current = 0; //reset current to 0
}
oFile << "\nmode: " << mode << endl; //output "mode"
return 0;
}
Try with
instead of
in the last
if
, orprevious
is ever zero and the lastx
(matching with itself wheny
is equal tox
) generate acurrent
greater thanprevious
(that is zero).OT: look at this
while
There is no need to sort the vector after every single insertion. I suggest you to add in
list
all the content of the input file and, after, sort the vector. Only one time, only after the last insertion.Something like