I'm trying to split a 16 digits number into digits. Using unsigned long int
and %
doesn't work because this type of variable only supports numbers smaller than 4.294.967.295. So I adapted the code and used fmod
instead of %
, but now the only result I get is zero.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
int main() {
setlocale(LC_ALL, "");
double num, digit;
int i;
printf("Enter the 16-digit number: ");
scanf("%lf", &num);
for (i = 1; num > 0; i++) {
printf("%d - ", i);
digit = fmod(num, 10.0);
printf("%.2lf ", digit);
num /= 10.0;
printf("%.2f\n", num);
}
}
What am I doing wrong?
fmod
is not the right tool to handle large integers, not is the double
type if you wish to have exacts digits. Type unsigned long int
might indeed not be large enough for numbers as large as 1016, depending on the target architecture, especially legacy systems where the long
type only has 32 bits even in 64-bit mode.
You should use the type unsigned long long int
, which is guaranteed to have at least 64 value bits, more than enough for your large integers:
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned long long num;
int i, digit;
printf("Enter the 16-digit number: ");
if (scanf("%llu", &num) == 1) {
for (i = 1; num > 0; i++) {
printf("%d - ", i);
digit = num % 10;
printf("%d ", digit);
num /= 10;
printf("%llu\n", num);
}
}
return 0;
}