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
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有