我有一个程序接收一个充满数字(5 位 - 1 位)的数据文件,对其进行排序,然后计算平均值。
问题是,出于某种奇怪的原因,我似乎得到了随机数。例如,这是输出文件的示例(由于某种原因它每次都会更改):
-1634367306
-1461109043
-542664683
-542664639
-542664491
-2
-1
-1
0
0
最后...
2003150324
2003165000
2003165000
2003165011
2003165011
2003165090
2003195799
2003196010
2003196054
2003284685
2003834952
2006176524
2006176524
2006221796
2006221796
输入文件中的数字是 0 - 99999,所以我不知道为什么会出现这些数字。
这是我同时为它编写的代码:
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
void getData(int[], int);
void outputData(int[], int);
double calcAverage(int[], int);
int findHighest(int[], int);
int findLowest(int[], int);
void removeDuplicates(int[], int);
void selectionSort (int[], int);
int main() {
const int SIZE = 1000;
int table[SIZE];
getData(table, SIZE);
selectionSort(table, SIZE);
cout << "Highest number: " << findHighest(table, SIZE) << endl;
cout << "Lowest number: " << findLowest(table, SIZE) << endl;
cout << "Average: " << calcAverage(table, SIZE) << endl;
outputData(table, SIZE);
}
/** selectionSort
** - Sorts an array of numbers
**/
void selectionSort(int array[], int size) {
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minValue = array[startScan];
for (int index = startScan + 1; index < size; index++) {
if (array[index] < minValue) {
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
/** getData
** - Opens a file of a set of numbers
** - Reads data from file into an array of numbers
**/
void getData(int table[], int size) {
ifstream iFile;
iFile.open("numbers.txt");
if (!iFile) {
cout << "File failed to load, please try again." << endl;
return;
}
for (int i = 0; i < size; i++) {
iFile >> table[i];
}
iFile.close();
}
/** outputData
** - outputs a sorted array of numbers to a text file
**/
void outputData(int table[], int size) {
ofstream oFile;
oFile.open("entry.txt");
for (int i = 0; i < size; i++) {
oFile << table[i] << endl;
}
oFile.close();
}
/** calcAverage
** - Calculate and return average of all data entries
**/
double calcAverage(int table[], int size) {
double total = 0;
for (int i = 0; i < size; i++) {
total += table[i];
}
return total / size;
}
/** findHighest
** - return highest number from array
**/
int findHighest(int table[], int size) {
int high = 0;
for (int i = 0; i < size; i++) {
if (table[i] > high)
high = table[i];
}
return high;
}
/** findLowest
** - return lowest number from array
**/
int findLowest(int table[], int size) {
int low = findHighest(table, size);
for (int i = 1; i < size; i++) {
if (table[i] < low)
low = table[i];
}
return low;
}
最高、最低、平均的典型结果,显示:
Highest number: 2006221796 Lowest number: 2006221796 Average: 2.71055e + 007
不知道我在这里弄错了什么。没有编译器错误,我很确定一切都已正确初始化。
最佳答案
'输入文件是无序的,有 921 行数字' - 那么你的程序如何知道有多少项被读入数组?您声明 const int SIZE = 1000;
并将该值用作排序范围 - 因此您正在对数组的 79 个未初始化项进行排序,这些数据不在您的输入中,
关于c++ - 输出文件中出现非常大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23147631/