C: ¿Cómo separar un número de varios dígitos en variables separadas?
Pregunta
Digamos que tengo un entero de varios dígitos en C. Quiero dividirlo en enteros de un solo dígito.
123
se convertiría en 1
, 2
, y 3
.
¿Cómo puedo hacer esto, especialmente si no sé cuántos dígitos tiene el entero?
Solución
int value = 123;
while (value > 0) {
int digit = value % 10;
// do something with digit
value /= 10;
}
Otros consejos
Primero, cuente los dígitos:
unsigned int count(unsigned int i) {
unsigned int ret=1;
while (i/=10) ret++;
return ret;
}
Luego, puede almacenarlos en una matriz:
unsigned int num=123; //for example
unsigned int dig=count(num);
char arr[dig];
while (dig--) {
arr[dig]=num%10;
num/=10;
}
Como una pista, obtener el enésimo dígito en el número es bastante fácil; dividir 10 n veces, luego mod 10 o en c:
int nthdig(int n, int k){
while(n--)
k/=10;
return k%10;
}
Los últimos dígitos de 123 son 123 % 10. Puede abandonar el último dígito de 123 haciendo 123/10, usando la división de enteros, esto le dará 12. Para responder a su pregunta sobre "¿Cómo sé cuántos dígitos tiene" - Intente hacerlo como se describió anteriormente y verá cómo saber cuándo detenerse.
Creo que a continuación ayudará el código ...
temp = num;
while(temp)
{
temp=temp/10;
factor = factor*10;
}
printf("\n%d\n", factor);
printf("Each digits of given number are:\n");
while(factor>1)
{
factor = factor/10;
printf("%d\t",num/factor);
i++;
num = num % factor;
}
Podemos usar este programa como una función con 3 argumentos. Aquí está "mientras (a ++ <2)", 2 es el número de dígitos que necesita (puede dar como un argumento) reemplazar 2 sin dígitos que necesita. Aquí podemos usar "z/= pow (10,6)" Si no necesitamos los últimos dígitos, reemplazar 6 por el no de dígitos que no necesita (puede dar como otro argumento), y el tercer argumento es el número que necesita para romper.
int main(){
long signed c=0,z,a=0,b=1,d=1;
scanf("%ld",&z);
while(a++<2){
if(d++==1)
z/=pow(10,6);
c+=(z%10)*b;
z/=10;
b*=10;}
return c;}
//Based on Tony's answer
#include <stdio.h>
int nthdig(int n, int k){
while(n--)
k/=10;
return k%10;
}
int main() {
int numberToSplit = 987;
printf("Hundreds = %i\n",nthdig(2, numberToSplit));
printf("Tens = %i\n",nthdig(1, numberToSplit));
printf("Units = %i\n",nthdig(0, numberToSplit));
}
Esto da como resultado la siguiente impresión:
Cientos = 9
Decenas = 8
Unidades = 7
Hice esto basado en el código de @asaelr:
typedef struct digitsArrayPlusNumber {
uint32_t *baseAddress;
uint32_t number;
} digitsArrayPlusNumber;
digitsArrayPlusNumber *splitDigits (uint32_t inValue) {
// based on code from asaelr@stackoverflow.com
uint32_t inputValue = inValue;
//Count digits
uint32_t theCount = 1;
while (inputValue /= 10)
theCount++;
// put in array
uint32_t *arr = malloc(sizeof(uint32_t) * theCount);
uint32_t dig = theCount;
while (dig--) {
arr[dig]=inValue % 10;
inValue /= 10;
// printf ("%d\n", arr[dig]);
}
digitsArrayPlusNumber *dandn = malloc (sizeof(digitsArrayPlusNumber));
dandn->baseAddress = arr;
dandn->number = theCount;
return dandn;
}
int main(int argc, const char * argv[]) {
for (int d = 0; d < splitDigits(12345678)->number; d++)
printf ("%u\n", (splitDigits(12345678)->baseAddress)[d]);
}
Funciona bastante bien, gracias!
Pruebe este código si desea separar los dígitos en el mismo orden sin usar matrices.
//Separate number digits
#include <stdio.h>
#include <math.h>
void main()
{
int x, y, n = 0;
scanf("%d", &x);
//counting digits
y = x;
while (y != 0)
{
n += 1;
y /= 10;
}
//printing separated digits
int i;
for (i = ceil(pow(10, (n - 1))); i != 0; i /= 10)
printf("%d ", (x / i) % 10);
}
Puede usar %10, lo que significa el resto si el número después de dividirse. Asi que 123 % 10
es 3, porque el resto es 3, suscente el 3 de 123, luego es 120, luego divide 120 con 10, que es 12. y hace el mismo proceso.
Puede dividir y conquistar, pero ha reescribido todas las bibliotecas aritméticas. Sugiero usar una biblioteca de precisión múltiple https://gmplib.org Pero, por supuesto, es una buena práctica
int l1; //123456 for example
scanf("%d",&l1);
char s[sizeof(l1)];
sprintf(s,"%5d",l1);'
//This will give you separate digits of the number in char format inside s[0],s[1]
//and so on.
//If you want them in int format, declare a int array say int i[sizeof(l1)] and add
//the following code
for(int c=1;c<=sizeof(l1);c++){
i[c] = s[c] - '0';
}
//Now i[0], i[1] etc will have the digits in int format