Identify a third in a decimal number

0

How can I identify a third of a decimal number with 5 digits after the period. in c #. Ex. If we have:

0.15171 = if it is third From (1)

0.17902 = is not tercia.

0.79277 = if it is tertiary.De (7)

    
asked by Luis García 21.09.2017 в 17:37
source

2 answers

1

Convert the number to string and create some function that counts how many times each character appears, if that function returns 3 you would have the third you want

    
answered by 21.09.2017 в 19:37
1

Although I imagine it is a school work in which the goal is to practice loops etc .., I will add a possible answer because I find it interesting to demonstrate the simplicity that LINQ gives us for tasks of this type. This example works for any number of digits, not just for 5:

decimal numero = 0.7927979M;

//Obtenemos el separador decimal del sistema para poder separar la parte decimal
char decimalSeparator = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
string parteDecimal = numero.ToString().Split(decimalSeparator)[1]; //obtenemos la parte decimal
var tercias = parteDecimal.Select(x => int.Parse(x.ToString())) //separamos cada uno de los digitos 
                          .GroupBy(x => x)                      //agrupamos por digito
                          .Where(x=>x.Count()==3);              //y nos quedamos con los que sean 3

foreach (var tercia in tercias)
{
    Console.WriteLine(String.Format("El número {0} es tercia de {1}", numero, tercia.Key));
}

//Salida por consola con este ejemplo:
//El número 0,7927979 es tercia de 7
//El número 0,7927979 es tercia de 9
    
answered by 22.09.2017 в 11:36