I have problem in finding the min and max of floating numbers in txt file. The number are stored in a file as one number per line. The Programm should go through these numbers and find the biggest and smallest number.
Let say i have the following numbers(two digits after comma and four digits before):
0005.00 0005.23 52340.53 0000.01 0111.10 0001.00 2523.00
When i run it i get weird results! Any help is appreciated.
#include<fstream>
#include<cstdlib>
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter=0, number;
float sum = 0, average=0;
char file_name [20];
cout << "enter filename: ";
cin >> file_name;
ifstream input;
input.open(file_name);
if (! input)
{
cout << "Can't open file" << file_name;
//exit (0);
}
input >> number;
float min = number;
float max = number;
while (input>>number)
{
counter++;
sum=sum+number;
// Now, we can also check for Min/Max...
if (number > max) max = number;
if (number < min) min = number;
}
average=sum/counter;
cout<< fixed<<cout.precision(3);
cout<< "The average file in file test is was "<<average<<endl;
cout<< fixed<<cout.precision(3);
cout<<"The largest number is: "<<max<<endl;
cout<< fixed<<cout.precision(3);
cout<<"The smallest number is: "<<min<<endl;
input.close();
return 0;
}
The results:
6The average file in file test is was nan
3The largest number is: 5.000
3The smallest number is: 5.000
Aucun commentaire:
Enregistrer un commentaire