I have an assignment that I am needing some guidance on. I need to find the highest/lowest value from an input file (along with the average, sum, and number of numbers, which I have already done). Following is my code:
/**********************************************************************************
Comments
***********************************************************************************/
#include <iostream>
#include <fstream>
usingnamespace std;
int main ()
{
double sum=0.0;
double average=0.0;
int zNumber=0;
int numbers=0;
double lowest = 999999;
double highest = 1;
ifstream randomFile;
randomFile.open("C:\\Users\\Big Rigg\\Desktop\\Random.txt");
if (randomFile.fail())
cout << "File cannot be opened.";
else
{
while (randomFile >> zNumber)
{
numbers++;
sum+=zNumber;
}
if (numbers>0)
{
average = sum/numbers;
}
else
average=0.0;
if (zNumber < lowest )
{
lowest = zNumber;
}
if (zNumber > highest )
{
highest = zNumber ;
}
cout << "The number of numbers is: " << numbers << endl;
cout << "The sum of the numbers is: " << sum << endl;
cout << "The average of the numbers is: " << average << endl;
cout << "The lowest number is: " << lowest << endl;
cout << "The highest number is: " << highest<< endl;
}
cin.ignore().get();
return 0;
}
Both the highest and lowest number variables are returning the same number, and neither is the highest or lowest number from the input... Any guidance would be appreciated.
/**********************************************************************************
Comments
***********************************************************************************/
#include <iostream>
#include <fstream>
usingnamespace std;
int main ()
{
double sum=0.0;
double average=0.0;
int zNumber=0;
int numbers=0;
double lowest = 999999;
double highest = 1;
ifstream randomFile;
randomFile.open("C:\\Users\\Big Rigg\\Desktop\\Random.txt");
if (randomFile.fail())
cout << "File cannot be opened.";
else
{
while (randomFile >> zNumber)
if (zNumber > highest )
{
highest = zNumber ;
}
elseif (zNumber < lowest )
{
lowest = zNumber;
}
{
numbers++;
sum+=zNumber;
}
if (numbers>0)
{
average = sum/numbers;
}
else
average=0.0;
cout << "The number of numbers is: " << numbers << endl;
cout << "The sum of the numbers is: " << sum << endl;
cout << "The average of the numbers is: " << average << endl;
cout << "The lowest number is: " << lowest << endl;
cout << "The highest number is: " << highest<< endl;
}
cin.ignore().get();
return 0;
}
Forgive the formatting; I created it in a hurry.
I still don't understand HOW these if statements find the highest and lowest number... In my head, this is how it's working:
The highest variable is initialized with a low number, then if the input file is larger than this low number, I'm assigning highest = input file
This certainly works, but I can't wrap my head around why...
EDIT: And the remaining equations (sum, average, count) are now incorrect... Terrific.