I require a method that can count the even digits in the programming language C #, thanks ....
public void Contador_Digitos_Pares(int dato)
{
//logica de la operacion.
return dato;
}
I require a method that can count the even digits in the programming language C #, thanks ....
public void Contador_Digitos_Pares(int dato)
{
//logica de la operacion.
return dato;
}
You could transform your number into string
to get the number of digits, go through them and check whether or not they are even
string numeroString = dato.ToString();
int numerosPares = 0;
for (int i = 0; i < numeroString.Length; i++)
{
if ((int.Parse(numeroString[i].ToString()) % 2) == 0)
{
numerosPares++;
}
}
Console.WriteLine("Total numeros pares: "+ numerosPares);
To check if a number is, or not even, it is best to use check if, by dividing by 2, its remainder is 0, in essence, if the condition num % 2 == 0
implies that num
is even, then, there are lots of possibilities to do what you are looking for, one could be using foreach
static int contarParesConForeach(int d)
{
int cont = 0;
foreach(char c in d.ToString())
{
if (Convert.ToInt16(c) % 2 == 0)
{
cont++;
}
}
return cont;
}
Another could be using Linq
with Where
and Count
static int contarParesCount(int d) => d.ToString().Where(x => x % 2 == 0).Count();
Both functions will produce exactly the same result
Console.WriteLine($"{contarParesConForeach(623)}");
//Output: 2
Console.WriteLine($"{contarParesCount(623)}");
//Output: 2
A page where you will find methods in C # .... I have the solution to your problem, I would recommend, if you are going to use them in a button, put this method of bass, not within the action of the button: