To find out why you are getting the 7 instead of the 5, you need to do some serious diagnostic printing — maybe using code something like this:
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
int n = 125521;
int d = floor(log10(n));
printf("n = %d: %d Digits\n", n, d + 1);
int t = 0;
while (floor(log10(n)) >= t)
{
printf("t = %d: n = %d; L = log10(n) = %f; F = floor(L) = %f\n",
t, n, log10(n), floor(log10(n)));
printf(" T = F-t = %f;", floor(log10(n)) - t);
printf(" P = pow(10,T)= %f\n", pow(10, floor(log10(n)) - t));
printf(" I = (int)P = %d; D = n/I = %d; M = D %% 10 = %d\n",
(int)pow(10, floor(log10(n)) - t),
n / (int)pow(10, floor(log10(n)) - t),
n / (int)pow(10, floor(log10(n)) - t) % 10);
printf("%d-----%d\n", (n / (int)pow(10, floor(log10(n)) - t) % 10), t);
t++;
}
return 0;
}
I've modified the loop condition; the old-style Fortran II arithmetic if
condition really isn't good style in C. It also prints the last digit. It would be better if the loop were written for (int t = 0; t <= d; t++)
, but I've not made that change.
On a Mac running OS X 10.10.3, using GCC 5.1.0 compiling a 64-bit program, the result is:
n = 125521: 6 Digits
t = 0: n = 125521; L = log10(n) = 5.098716; F = floor(L) = 5.000000
T = F-t = 5.000000; P = pow(10,T)= 100000.000000
I = (int)P = 100000; D = n/I = 1; M = D % 10 = 1
1-----0
t = 1: n = 125521; L = log10(n) = 5.098716; F = floor(L) = 5.000000
T = F-t = 4.000000; P = pow(10,T)= 10000.000000
I = (int)P = 10000; D = n/I = 12; M = D % 10 = 2
2-----1
t = 2: n = 125521; L = log10(n) = 5.098716; F = floor(L) = 5.000000
T = F-t = 3.000000; P = pow(10,T)= 1000.000000
I = (int)P = 1000; D = n/I = 125; M = D % 10 = 5
5-----2
t = 3: n = 125521; L = log10(n) = 5.098716; F = floor(L) = 5.000000
T = F-t = 2.000000; P = pow(10,T)= 100.000000
I = (int)P = 100; D = n/I = 1255; M = D % 10 = 5
5-----3
t = 4: n = 125521; L = log10(n) = 5.098716; F = floor(L) = 5.000000
T = F-t = 1.000000; P = pow(10,T)= 10.000000
I = (int)P = 10; D = n/I = 12552; M = D % 10 = 2
2-----4
t = 5: n = 125521; L = log10(n) = 5.098716; F = floor(L) = 5.000000
T = F-t = 0.000000; P = pow(10,T)= 1.000000
I = (int)P = 1; D = n/I = 125521; M = D % 10 = 1
1-----5
You should run either this program or something very similar and show the results of the intermediate calculations. We can then, maybe, begin to understand why you see a 7 instead of a 5.