You are here:

C++/minimum of 4 values

Advertisement


Question
Hey Eddie,

This has been bugging me. How do I detect the minimum of 4 given values? This is the fraction of what I did which I know is not right 'cause it obviously doesn't give the right answer.

i have my values initialised in my main where
x1=6, x2=4, x3=4.3, x4=7.9

double minimum(double x1, double x2, double x3, double x4)
{
   double min;
   min = x1; //assuming x1 is min

   if (x2 < min)
   {
      min = x2;
   }
      else
      {
         if (x3 < min)
        {
         min = x3;
         }

         else
         {
         if (x4 < min)
         {
         min = x4;
         }

         }
     }

   return min;
}

I didn't exactly get the right answer. It works for some because coincidently, that value happened to be the lowest. Don't think I'm explaining myself well.. but the bottom line is, how do I create a funtion that detects the minimum of 4 values. It works if there's 3 values, or 2.. but not 4. And I've been figuring out and still not too sure about it.

Looking forward for a feedback. Thank you so much!

Answer
Hello epic, thank you for the question.

Your problem if the fact that you are not using else if's in your conditional statement. The execution flow is not working how you think it is. Here is what it should look like (note AllExpert's lack of indentation preservation):

double minimum(double x1, double x2, double x3, double x4)
{
double min = x1;

if (x2 < min)
{
  min = x2;
}
else if(x3 < min)
{
  min = x3;
}
else if(x4 < min)
{
  min = x4;
}
return min;
}

That should have you good to go. Please don't hesistate to ask another question if you do not understand something.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.