Hello,
I would like to pass an array number into a function. I get an error saying i was not declared. Please explain why what im doing is wrong. Thank you!
/*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>
usingnamespace std;
double average (int , double []),
minimum (double []),
maximum (double []),
avg, min, max;
int main()
{
double darr[1000],
avg,min,max;
int inputNum;
ifstream inputFile;
inputFile.open ("numbers.txt");
if (inputFile)
{
cout << "Please enter positive double values"
<< "How many values would you like to read in?";
cin >> inputNum;
if ( inputNum > 0 && inputNum < 1001)
{
for (int i = 0; i < inputNum; i++)
inputFile >> darr[i];
avg = average (inputNum, darr);
cout << "The average number is " << avg << endl;
min = minimum (darr);
cout << "The smallest number is " << min << endl;
max = maximum (darr);
cout << "The largest number is " << max << endl;
}
}
else
{
// Display an error message.
cout << "Error opening the file.\n";
}
inputFile.close();
return 0;
}
double average (int num, double arr[])
{
double sum = 0.0;
for(int i = 0; i < num; i++ )
sum = sum + arr[i];
return sum/num;
}
double minimum (double arr[])
{
double smallest = 0.0;
if (arr[i] <= smallest)
smallest = arr[i];
return smallest;
}
double maximum (double arr[i])
{
double largest = 0.0;
if (largest <= arr[i])
largest = arr[i];
return largest;
}
There double maximum (double arr[i])
Edit: ups, and you haven't declare varable i inside Minimum and Maximum function
And I thnk you'll also need to pass var inputNum to Maximum and Minimum function as well and change both of this function to
1 2 3 4
for(int i=0;i<inputNum;i++){
if(largest < or > arr[i])
largest=arr[i]
}
i replied before you edited, everything works thanks! One more question, when i run the program the second time it seems that the numbers that were used the first time are deleted from the file, is there anything i can use to keep the file constant so that the same # of doubles is there every time i run the program?
Lets say that the numbers in a file are
30
11
23
56
45
43
and the first time the user types in 3 and 30, 11 and 23 get used. After this run the file looks like this;
56
45
43
My question is how do i keep it original, with all the numbers that were there in the beginning, after numerous runs?