C++/minimum of 4 values
Expert: Eddie - 9/8/2006
QuestionHey 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!
AnswerHello 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