1

I am working on a function to find the lowest value within 5 input doubles. I found a reference online. I have tried to do my code using arrays, however I receive the following error: Error: Thread 1: EXC_BAD_ACCESS (Code =1, address = 0x7fff5fc89000)

Can you please advise where my code is wrong? Appreciate it!

Online Reference:

int findLowest(int s1, int s2, int s3, int s4, int s5)
{
         int lowest = s1; 
         
         
    if (s2 < lowest )        
         {
                  lowest = s2;
         }
         else if (s3 < lowest)
         {
                  lowest = s3;
         }
         else if (s4 < lowest)
    {
                  lowest = s4;
         }
         else if (s5 < lowest)
         {
                  lowest = s5;
         }
  
         cout << "The lowest test score is: " << lowest << endl;
  
    return lowest;
}

Source: http://cboard.cprogramming.com/cplusplus-programming/149549-lowest-score-drop-assignment.html

My Code with Arrays:

double findLowest(double a, double b, double c, double e, double f)
{
    // creating an array numberRange[] to read the 5 input double 
    //values
    double numberRange[5] = {a,b,c,e,f}; 

    // creating a variable minimum and assigning it the value of the 
    //first item in the numberRange[] array
    double minimum = numberRange[0];    

    // looping through the numberRange array
    for(int counter = 1; sizeof(numberRange)/sizeof(*numberRange) ; counter++ ) 
    // To get the number of elements in an array, you have to divide 
    // the size of the array by the size of each element
    {
         // checking if the numberRange value at the counter is less 
         // than the minimum value. If true, the minimum value is 
         //replaced with a new value.
        if ( numberRange[counter] < minimum ) 
        {
            minimum = numberRange[counter];
        }

    }

   return minimum;
}

Error: Thread 1: EXC_BAD_ACCESS (Code =1, address = 0x7fff5fc89000)

ab_dev
  • 93
  • 8

2 Answers2

1

The problem is your for loop test:

for(int counter = 1; sizeof(numberRange)/sizeof(*numberRange) ; counter++ )
//            this   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ is always true!

Why not just make it counter < 5?

TowerFan
  • 210
  • 1
  • 10
0

Your for loop's stop condition is pretty unusual. Also you're starting counting from 1 (why not 0)? How about a just doing:

double numberRange[5] = {a,b,c,e,f}; 
return *std::min_element(numberRange);
Inverse
  • 4,408
  • 2
  • 26
  • 35
  • OP uses `numberRange[0]` to initialize `min`, so the comparisons start from the second element... – Bob__ May 21 '16 at 19:33
  • Shouldn't it be `*std::min_element(std::begin(numberRange),std::end(numberRange))`? – Bob__ May 21 '16 at 20:07