const int SIZE = 10;
int numbers[SIZE] = {15, 6, 3, 11, 22, 4, 0, 1, 9, 12};
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 將包含陣列中的最低值。
62458 81598 98745 53460 35678 86322
89920 78960 124569 43550 45679 98750
#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; }程式輸出結果為:
Total sales $899689.00
Average sales $ 74974.08
Highest sales $124569.00
Lowest sales $ 35678.00