I just wanted to write a minimalistic program in C to calculate the sum of digits of some natural number (the sum of digits is defined as follows: sumOfDigits(123) = 6, sumOfDigits(0) = 0, sumOfDigits(32013) = 9, and so on).
So far, everything is ok with the following code snippet. For example, for 5100 it delivers 6, correctly. But, why is 14 delivered for 05100 (remember the leading 0)?
What's going on here?
I had a look at the binary representation of the numbers, but that didn't give any information to me. (BTW: The following code should run anywhere, I guess.)
#include <stdio.h>
unsigned int sumOfDigits(unsigned int n) {
int retval = 0;
while (n > 0) {
retval += n % 10;
n/=10;
}
return retval;
}
int main() {
printf("OK: %u
", sumOfDigits(5100u));
printf("WTF: %u", sumOfDigits(05100u));
return 0;
}
EDIT: As Zaibis stated .... a leading 0 means octal notation. :-) and so: 5100_8 == 2624_10
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…