用于查找数组中最高值(其实就是最大值,但是为对应源代码中的 highest,故仍称为最高值)和最低值(其实就是最小值,但是为对应源代码中的 lowest,故仍称为最低值)的算法非常相似。首先,来看一下在数组中寻找最高值的代码。假设在程序中出现了以下语句。
查找数组中最高值的代码如下所示:
- int count;
- int highest;
- highest = numbers[0];
-
- for (count = 1; count < SIZE; count++)
- {
- if (numbers[count] > highest)
- highest = numbers[count];
- }
首先,该语句将第一个数组元素中的值复制到名为 highest 的变量中。然后,循环将从下标 1 开始的所有其余数组元素与存储在 highest 中的值进行比较。每次当它发现数组元素中的值大于 highest 中的值时,都会将其复制到 highest。循环完成后,highest 将包含数组中最的值。
以下代码将找到数组中的最低值。对比之后可以发现,它与查找最高值的代码几乎相同。
- int count;
- int lowest;
- lowest = numbers[0];
- for (count = 1; count < SIZE:count++)
- {
- if (numbers[count] < lowest);
- lowest = numbers[count];
- }
当循环完成后,lowest 将包含数组中的最低值。
下面的程序将创建月度销售报告,它演示了查找数组中总和、平均值、最高值和最低值的算法。它将算法结合起来,在一个循环中即可找到最高值和最低值。用于填充数组的销售数据是从 sales.dat 文件中读取的,该文件包含以下值:
实现代码为:
- #include <iostream>
- #include <fstream> // Needed to use files
- #include <iomanip>
- using namespace std;
-
- int main()
- {
- const int NUM_OFFICES = 12;
- ifstream dataIn;
- int office; // Loop counter
- double sales[NUM_OFFICES], // Array to hold the sales data
- totalSales = 0.0, // Accumulator initialized to zero
- averageSales,
- highestSales,
- lowestSales;
-
- // Open the data file
- dataIn.open("sales.dat");
- if (!dataIn)
- cout << "Error opening data file.\n";
- else
- {
- //Fill the array with data from the file
- for (office = 0; office < NUM_OFFICES; office++)
- dataIn >> sales[office];
- dataIn.close();
-
- // Sum all the array elements
- for (office = 0; office < NUM_OFFICES; office++)
- totalSales += sales[office];
- // Calculate average sales
- averageSales = totalSales / NUM_OFFICES;
-
- //Find highest and lowest sales amounts
- highestSales = lowestSales = sales[0];
- for (office = 1; office < NUM_OFFICES; office++)
- {
- if (sales[office] > highestSales)
- highestSales = sales[office];
- else if (sales[office] < lowestSales)
- lowestSales = sales[office];
- }
- // Display results
- cout << fixed << showpoint << setprecision(2);
- cout << "Total sales $" << setw (9) << totalSales << endl;
- cout << "Average sales $" << setw(9) << averageSales << endl;
- cout << "Highest sales $" << setw(9) << highestSales << endl;
- cout << "Lowest sales $" << setw (9) << lowestSales << endl;
- }
- return 0;
- }
程序输出结果为: