I suspect that the pow()
is not numerically stable on that platform you're using. You will get 24
, if pow(10, 2)
returns a double
that is little less than 100, e.g. 99.9999999998765, which when cast to (int) would be truncated, resulting in 99
, and thus you get 123 % 99 == 24
. You could test what is the output of
printf("%.100f\n", pow(10, 2));
If that be the case, and since it seems you're really doing integer math, I'd have another loop variable for multiples of 10:
int tens;
for (i = 1, tens = 10; i < n; i++, tens *= 10) {
temp = a % tens;
printf(tens);
}
(Additionally, the initial version of the code had the following problems: the variable int temp;
was read uninitialized (and #include <math.h>
was missing by mistake). Thus the code had also undefined behaviour.
The C11 standard appendix J2 says that among others, the behaviour of a program is undefined, when:
An lvalue designating an object of automatic storage duration that could have been declared with the register
storage class is used in a context that requires the value of the designated object, but the object is uninitialized. (6.3.2.1).
P.S. The while (temp >= 0)
condition is needless (and that is a cause for undefined behaviour), except for a complicated way to ensure that a positive integer is entered; as you'd break out anyway at temp == 0
, so you could replace it with while (1)
)