Don Su
Don Su

Reputation: 139

Comparing Real Numbers in an Array

I have an array called Marks, that contains 5 elements. I want to loop through the array, and get the highest item in the Marks array. When I run the below code I get 23.45

var
 Marks: array[0..4] of real = (42.4,65.34,24.12,23.45,43.24);
 iHighest : real;
 iInt : integer;
begin
 iHighest := Marks[0];
 for iInt:= 0 to 4 do
  begin
   if (iHighest >= Marks[iInt]) then
    iHighest := Marks[iInt];
  end;
end;
ShowMessage('Highest Mark: ' + FloatToStr(iHighest)); // Returns 23.45

But when I change the if statement to if (Marks[iInt] >= iHighest) the showmessage returns the correct answer of 65.34. Please can you let me know what is the difference.

Upvotes: 0

Views: 198

Answers (2)

Rudy Velthuis
Rudy Velthuis

Reputation: 28846

You want to find the highest number. For that, your condition is wrong. Your code finds the lowest number.

Example of what happens in your code: At some point in time, iHighest is 42.4; iInt is 2, so Marks[iInt] is 24.12. Then iHighest >= 24.12, so it becomes 24.12! In others words, the new value of iHighest is lower than the initial value.

But, if you want to find the highest number, then only if the currently investigated number (Marks[iInt]) is higher than the current iHighest, you update iHighest.

And since you initialize iHighest with the first element (index 0) anyway, you only have to check the others:

for iInt := 1 to 4 do            // not: 0 to 4
  if Marks[iInt] > iHighest then // not the other way around
    iHighest := Marks[iInt];

Note that there is no need to check with >= either. You only update iHighest if the current value is higher, not if it is equal.


The best way to find out such errors by yourself is by debugging. The Delphi debugger is very easy to use and can show you step by step, line by line, how values change. If you had used the debugger, you would have seen how, in your code iHighest would take on a lower value, not a higher one, on each update.

Just read the online help on using the debugger. It is much easier than you think.

Upvotes: 2

Harmaen Khan
Harmaen Khan

Reputation: 15

iHighest is for marking greatest number. You have to change it if it is smaller than Marks[iInt], so true condition will be iHighest < Marks[iInt] or Marks[iInt] > iHighest

Hope you got it.

Upvotes: 2

Related Questions