Right now my program works but I would like the program to return the fielddata[i].Field value with the highest Yph value.
FieldID are int's and Yph are floats
this is the piece of code i need to fix
1 2 3 4 5 6 7
for (int i = 0; i < 8; i++)
{
if (fielddata[i].Yph > highyph)
highyph = fielddata[i].Field;
}
cout << "The Field with the Highest Yield is " << highyph << endl;
It is hard to follow with the variable names you used, but it looks like you are trying to get a real number from an integer. An integer value does not go past the the decimal point. In other words, there is no difference between 2.1 and 2.9, they both equal 2.
1 2 3 4 5 6 7
if (fielddata[i].Yph > highyph)
highyph = fielddata[i].Field;
//if (float > float)
// float= integer;
// all that aside, if I understand right, this would be a better start
if(fielddata[i].Yph > highyph)
highyph = fielddata[i].yph; // now just designate field as highest
In other words, you are reading data from a completely different stream than the one you just opened.
Just one reason why global variables should be avoided, they are hard to keep track of. (there are other reasons to avoid them). Delete the variable definition at line 8: std::ifstream infile("fields.txt");
You need two separate variables, one to hold the highest value of Yph and another to hold the corresponding value of Field. Whenever you change the value of one, change the other too.
Or alternatively - just use a variable of type Fields
instead of
float highyph = 0;
you could have
1 2
Fields highf;
highf.Yph = 0;
Then store the whole object when a new high value is found: highf = fielddata[i];
Slightly different from Cervil's suggestion, I'd just maintain a variable that is the position of the best item in the array. This is better because it's just one variable instead of two, and it's a small variable (a size_t) instead of a potentially giant one (a Field).
1 2 3 4 5 6 7
size_t pos = 0;
for (int i = 0; i < 8; i++) {
if (fielddata[i].Yph > fielddata[pos].Yph) {
pos = i;
}
}
cout << "The Field with the Highest Yield is " << fielddata[pos].Field << endl;