Function Return Error

Hi, I’m pretty new with functions and was wondering what I could do differently here. Ideally I’d like the function to sort the two numbers given and give me the number that’s closest to 100 (without going over). Currently getting a “This method must return a result type of int” error.

void setup()
{
  println(functionName(18,25));
}

int functionName(int firstNumber, int secondNumber)
{
  if (firstNumber > 0 && secondNumber > 0 || (firstNumber < 100 && secondNumber < 100))
  {
    if (firstNumber >= secondNumber && firstNumber < 100)
    {
      return firstNumber;
    }
    else if (secondNumber >= firstNumber && secondNumber < 100)
    {
      return secondNumber;
    }
  }
  else
  {
    return 0;
  }
}
1 Like

Yeah.

all possible ways the functions can be executed must return something.

BUT the first if-clause contains some if..else if...-construct that doesn’t have an else block.

that’s the problem

result is 25 here by the way

Warm regards,

Chrisir

Hey and welcome to the forum!

Great to have you here!

1 Like

Hmm okay, so I either need to add an else to the else if or somehow keep the parameters and delete the if that’s attached?

But there are other ways to do it. For example check the distance to 100 and then pick the number that is closer to 100 when it’s <100

That’s what I did

Chrisir

1 Like

Okay I’ll have to play around with it some more, thanks for the help!

1 Like

here is my version, haven’t tested with other numbers though

I made a description above

maybe you can use

if( abs(100 - a) < abs(100 - b) ) {
   // a is closer to 100
   if(a<100) 
      return a; 
   else if (b<100) return b; 
   else return 0; 
} else {
   // b is closer to 100
   .....
}

My old version



void setup() {
  size(300, 300); 
  println(functionName(18, 25));
}

int functionName(int firstNumber, int secondNumber) {
  if (firstNumber > 0 && secondNumber > 0 || (firstNumber < 100 && secondNumber < 100)) {
    if (firstNumber >= secondNumber && firstNumber < 100) {
      return firstNumber;
    } else if (secondNumber >= firstNumber && secondNumber < 100) {
      return secondNumber;
    } 
    //+++++++++++++++++++++++++++++++++
    else {
      return 0;
    }
    //+++++++++++++++++++++++++++++++++
  } else {
    return 0;
  }
}

1 Like

How does abs work? Does it just check if it’s a positive number?

This answer to this is available in the references.

See:
https://processing.org/

:)

1 Like

That’s super useful! Than you

2 Likes

This helped a ton, thanks again!

2 Likes