Question

Somehow this code doesn't work, I get trash numbers as results. Can you guys have a look at it?

float * greatest(float *elements,int length){

float max=elements[0];int index=0;

for (int i = 1; i < length; i++)
{
    if(max<elements[length]){
        max = elements[length];
        index = length;}
}
return &elements[index];
}
Was it helpful?

Solution

if(max<elements[length]){

Will always return the last element, because the length never changes. You want

if(max<elements[i]){

OTHER TIPS

Apart from the indexing bug (elements[length] instead of elements[i]), C++ already has that built in, no need to reinvent the wheel:

#include <algorithm>
//...
float * greatest(float *elements,int length){
    return max_element(elements, elements+length);
}

The correct form is:

float * greatest(float *elements,int length){

float max=elements[0];int index=0;

for (int i = 1; i < length; i++)
{
    if(max<elements[i]){
        max = elements[i];
        index = i;}
}
return &elements[index];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top