1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
/*This program will read in up to 1000
positive numbers, average them, and
find the maximum and min minimum
*/
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
double average (int , double []),
minimum (int, double []),
maximum (int, double []),
avg, min, max;
int main()
{
double darr[1000],
avg,min,max;
char answer;
int inputNum;
ifstream inputFile;
inputFile.open ("numbers.txt");
if (!inputFile){
// Display an error message if value is <0 or >1001
cout << "Error opening the file.\n";
exit (1);
}
else {
cout << "Please enter positive double values \n"
<< "and I will display the smallest and largest \n"
<< "values and calculate the average. \n"
<< "\nHow many values would you like to read in? ";
cin >> inputNum;
if ( inputNum > 0 && inputNum < 1001) //Checks value entered for
{ // negative or invalid
for (int i = 0; i < inputNum; i++)
inputFile >> darr[i];
avg = average (inputNum, darr);
cout << "\nThe average number is: " << avg << endl;
min = minimum (inputNum, darr);
cout << "The smallest number is: " << min << endl;
max = maximum (inputNum, darr);
cout << "The largest number is: " << max << endl;
cout << "\nWould you like to enter another set of numbers?\n"
<< "Press Y for Yes to continue\n"
<< "or N for no or -1 to quit: ";
cin >> answer;
if ((answer == 'Y') || (answer == 'y')) //varifies if the user wants
//wants to continue
cout << "\nPlease enter number of doubles, nagative or N to quit ";
cin >> inputNum;
}
else
{
cout << "\nInvalid Number or No entered, Goodbye! ";
return 0;
inputFile.close();
}
}
}
//*******************************************************
// Functions
//*******************************************************
double average (int num, double arr[])
//This function calculate the average
{
double sum = 0.0;
for(int i = 0; i < num; i++ )
sum = sum + arr[i];
return sum/num;
}
double minimum (int num, double arr[])
//This function finds the smallest number
{
double smallest = 10000;
for (int i = 0; i < num; i++)
if (arr[i] <= smallest)
smallest = arr[i];
return smallest;
}
double maximum (int num, double arr[])
//This function finds the largest number
{
double largest = 0.0;
for (int i = 0; i < num; i++)
if (largest <= arr[i])
largest = arr[i];
return largest;
}
|