我正在开发一个程序,在给定输入文件中的值列表(double
s)的情况下,按升序对它们进行排序并计算mode
,并将结果打印在输出文件。这就是我到目前为止所提出的。
它应该做的是将模式分配给向量的x
元素,即为current
产生更大值的元素,但是当我运行此程序时,模式始终等于向量的最后一个元素。
我无法弄清楚我在做什么错误,因为在我看来它似乎完全符合逻辑。
非常感谢任何帮助。
#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;
}
答案 0 :(得分:1)
尝试
previous = current;
而不是
current = previous;
在上一个if
中,或previous
为零,最后x
(当y
等于x
时与自身匹配)生成current
大于previous
(即零)。
OT:看看这个while
while(iFile >> data)
{
list.push_back(data); //put the elements in a vector
sort(list.begin(), list.end()); //and sort them in ascending order
}
每次插入后都无需对矢量进行排序。我建议你在list
中添加输入文件的所有内容,然后对矢量进行排序。只有一次,仅在最后一次插入后。
像
这样的东西while(iFile >> data)
{
list.push_back(data); //put the elements in a vector
}
sort(list.begin(), list.end()); //and sort them only one time