Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
float max(float vec[], int len)
        {
            int i;
            float max;
            for (i = 0; i < len; i++) {
                if (vec[i] > max) {
                    max = vec[i];
} }
return max; }

however it doesn't work. How would i alter it??
Posted
Updated 9-Dec-15 14:11pm
v2
Comments
barneyman 9-Dec-15 20:11pm    
what value does max start with?
Member 12197225 9-Dec-15 20:16pm    
oooh is max meant to be initialised?
barneyman 9-Dec-15 20:24pm    
only if you want it to work :)
Member 12197225 9-Dec-15 20:25pm    
THAAAANNKKKSS!!
Sergey Alexandrovich Kryukov 9-Dec-15 20:26pm    
Ask yourself. The problem is solved, I hope...
—SA

1 solution

further to my commentsl, try this

max gets seeded with the first value, with an optimisation that ignores the loop if there's only one value in the array - technically not needed, the compiler optimiser will build the for loop to essentially do the same thing

i'm assuming the caller is checking for zero values

float max(float vec[], int len)
{
 // seed max with the first value
 float max=vec[0];
 // short cut
 if(len>1)
 {
  for (int i = 0; i < len; i++) 
  {
   if (vec[i] > max) 
   {
    max = vec[i];
   } 
  }
 }
 return max; 
}
 
Share this answer
 
v2
Comments
barneyman 9-Dec-15 20:31pm    
also, pass the array by reference max(float &vec[]) - code will be faster, especially for large arrays
PIEBALDconsult 9-Dec-15 20:54pm    
Isn't a C++ array a pointer anyway?
barneyman 9-Dec-15 21:06pm    
true
Matt T Heffron 10-Dec-15 12:39pm    
And in the for loop, i can start at 1 since max already holds vec[0]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900