Compare number within a numerical range

Asked

Viewed 3,830 times

3

I want to create a function that receives a number and check if it is within a range from 1 to 25. What is the best way to do this?

private int VerificaIntervalo(int numero)
{
    if (numero > 25)
    {
        return 0;
    }
    return 1;
}
  • 7

    if(numero >= 1 && numero <= 25) does not serve?

  • @Diegofelipe, your answer is right!

  • @itasouza Think you can accept any of the answers?

4 answers

5

It’s much simpler than other options:

private bool VerificaIntervalo(int numero) => numero >= 1 && numero <= 25;

I put in the Github for future reference.

Ideally the name of the method could be more explanatory than refers to this.

  • Yeah, I tried! + 1

  • Prolixity is a great evil.

  • 1

    @jbueno in code without uvida. In didactic texts, no :) What many people do not understand is that prolixity when teaching is a tool.

2

the simplest would be:

private bool VerificaIntervalo(int numero)
{
   if(numero >= 1 && numero <= 25)
     return true;
   else
     return false;
}
  • 2

    As opposed to if may use only return numero >= 1 && numero <= 25;.

  • yes, it would also be a good option

1

Here an example for you to check if the numbers are in the range 1 to 25, see below:

using System;

public class Test
{
    public static void Main()
    {
        if (comparaNumero(90))
           Console.WriteLine("Dentro do intervalo entre 1 a 25");
        else
           Console.WriteLine("Fora do intervalo");
    }

    public static bool comparaNumero(int n)
    {
        return (n >= 1 && n <= 25);
    }
}

See worked on Ideone.

0

private bool VerificaIntervalo(int numero)
    {
          if(numero >= 1 && numero <= 25)
          {
            return true;
          }
          else
          {
           return false;
          }
    }

Would that be?

  • Thank you for all your answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.