Hi
For a robot car I need to compare 5 distances. The program has to find the longest distance of these 5. So I wanted to ask what kind of comparison would be the best. I wrote one which used if & else. But its confusing and doesnt work.
Can anyone help me?
Put the 5 distances in an array. Name a variable to hold the max and give it a value of 0. Use a for loop to iterate through the array comparing each element (distance) to the max. If the current distance is greater than the max make it the new max.
int distances[] = {2, 9, 4, 12, 3};
int max = 0;
void setup()
{
Serial.begin(115200);
for(int n = 0; n < 5; n++)
{
if(distances[n] > max)
{
max = distances[n];
}
}
Serial.println(max);
}
void loop()
{
}
If you want to do it differently, post the code that you tried and describe what it does and how it is different than what you want.
Use an array.
Assume the answer is the first, put it in a variable.
Step through the array, if an entry is bigger than the variable, then it is the longest, so set the variable to its value.
When you reach the end of the array, the longest value will be in that variable.
You can do the same thing while the robot is running, without an array. After every trip, save the distance. If the current distance is greater than the previous, update the variable. At the end of 5 trips, capture the variable and reset the process.