Pointers

I have an assignment for my first computer science class and I have it all pretty much done but I am doing something wrong. I am getting the correct maximum number but the wrong minimum number in the file (it keeps saying that it is zero when there is no zero in the file). I'm sure it is a done mistake, but I would appreciate if you could tell me what I am doing wrong.

#include <iostream>
#include <fstream>

using namespace std;

double findMax(double*, int);
double findMin(double*, int);
int main () {
ifstream fin;
fin.open("numbers.txt");
if(fin.fail()){
cout<<"Error opening file.\nShutting down."<<endl;
return 0;
}

int total;
fin >> total;
cout << "There are " << total << " numbers in the file." << endl;

double *values;

values=new double[total];

for (int count=1; count<total; count++) {
fin >> values[count];
}

double max, min;

max=findMax(values, total);
min=findMin(values, total);

cout << "The largest number is " << max << "." << endl;
cout << "The address of te largest number is " << &max << "." << endl;
cout << "The smallest number is " << min << "." << endl;
cout << "The address of the smallest number is " << &min << "." << endl;

if (&max<&min)
cout << "The largest number comes before the smallest number in the file." << endl;
else if (&max>&min)
cout << "The smallest number comes before the largest number in the file." << endl;


return 0;
}

double findMax(double* values, int total){
int maxIndex=1;
double max;
for (int index=1; index<total; index++) {
if (values[index]>values[maxIndex])
maxIndex=index;
}
max=values[maxIndex];
return max;
}

double findMin(double* values, int total){
int minIndex=1;
double min;
for (int index=1; index<total; index++) {
if (values[index]<values[minIndex])
minIndex=index;
}
min=values[minIndex];
return min;
}

Thanks for the help.
Hi,
I can recreate your error if the first number in the file is not the count of numbers to follow.
when this is fixed the min and max work.

I also spotted in your code that you are starting loops with int index = 1,
index should start at zero, but if you want to keep them at 1 you will need
to add 1 to the condition.

1
2
3
4
5
6
    for (int i=0;i<total;i++)

or

    for (int i=1;i<total+1;i++)



Hope this helps
Shredded
The first number in the file is the count for the numbers that follow. And the reason that I started with index=1 is because I wanted to start at 1 and not 0 because the first number in the file is the count, so I didn't want to use it in the loop.
Topic archived. No new replies allowed.